classSolution { public: intfourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D){ unordered_map<int, int> countAB; for (int u: A) { for (int v: B) { ++countAB[u + v]; } } int ans = 0; for (int u: C) { for (int v: D) { if (countAB.count(-u - v)) { ans += countAB[-u - v]; } } } return ans; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { publicintfourSumCount(int[] A, int[] B, int[] C, int[] D) { Map<Integer, Integer> countAB = newHashMap<Integer, Integer>(); for (int u : A) { for (int v : B) { countAB.put(u + v, countAB.getOrDefault(u + v, 0) + 1); } } intans=0; for (int u : C) { for (int v : D) { if (countAB.containsKey(-u - v)) { ans += countAB.get(-u - v); } } } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9
classSolution: deffourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: countAB = collections.Counter(u + v for u in A for v in B) ans = 0 for u in C: for v in D: if -u - v in countAB: ans += countAB[-u - v] return ans
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13
var fourSumCount = function(A, B, C, D) { const countAB = newMap(); A.forEach(u => B.forEach(v => countAB.set(u + v, (countAB.get(u + v) || 0) + 1))); let ans = 0; for (let u of C) { for (let v of D) { if (countAB.has(-u - v)) { ans += countAB.get(-u - v); } } } return ans; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcfourSumCount(a, b, c, d []int) (ans int) { countAB := map[int]int{} for _, v := range a { for _, w := range b { countAB[v+w]++ } } for _, v := range c { for _, w := range d { ans += countAB[-v-w] } } return }