**Input:** nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
**Output:** 2
**Explanation:**
The two tuples are:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
**Input:** nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
**Output:** 1
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
// edge cases
if (A.length == 0) return 0;
// 2 maps
Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
int n = A.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int k1 = A[i] + B[j];
int k2 = C[i] + D[j];
map1.put(k1, map1.getOrDefault(k1, 0) + 1);
map2.put(k2, map2.getOrDefault(k2, 0) + 1);
}
}
// iterate 2 maps
int res = 0;
for (int k : map1.keySet()) {
if (map2.containsKey(-k)) { // find tuples
res += map1.get(k) * map2.get(-k);
}
}
return res;
}
}
actually one map is enough.
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
// edge cases
if (A.length == 0) return 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int n = A.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int k = A[i] + B[j];
map.put(k, map.getOrDefault(k, 0) + 1);
}
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int k = C[i] + D[j];
if (map.containsKey(-k)) { // find tuples
res += map.get(-k);
}
}
}
return res;
}
}