給定四個包含整數的數組列表 A、B、C、D,計算有多少個元組 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。爲了使問題簡單化,全部的 A, B, C, D 具備相同的長度 N,且 0 ≤ N ≤ 500 。全部整數的範圍在 -228 到 228 - 1 之間,最終結果不會超過 231 - 1java
使用 HashMap,將 A、B 分爲一組,C、D 分爲一組,首先求出 A 和 B 任意兩數之和 sumAB,以 sumAB 爲 key,sumAB 出現的次數爲 value,存入 HashMap 中。而後計算 C 和 D 中任意兩數之和的相反數 sumCD,在 hashmap 中查找是否存在 key 爲 sumCD,有則計數加一。算法時間複雜度爲 O(n2)算法
class Solution { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { Map<Integer, Integer> map = new HashMap<>(); int res = 0; for(int i = 0; i < A.length; i++) { for(int j = 0; j < B.length; j++) { int sumAB = A[i] + B[j]; if(map.containsKey(sumAB)) { map.put(sumAB, map.get(sumAB) + 1); } else { map.put(sumAB, 1); } } } for(int i = 0; i < C.length; i++) { for(int j = 0; j < D.length; j++) { int sumCD = -(C[i] + D[j]); if(map.containsKey(sumCD)) { res += map.get(sumCD); } } } return res; } }