Given four integer arrays A,B,C,D, which have the same length of N where 0 ≤ N ≤ 500, compute the number of tuples (i,j,k,l) such that A[i] + B[j] + C[k] + D[l] == 0.
Solution 1
We can use a map to count the numbers of all possible values of A[i] + B[j] , where 1 ≤ i,j ≤ N. Then we enumerate k and l, and add the number of -C[k]-D[l] to the answer. The time complexity is O(N^2).
Solution 2
We use array AB to store all possible values of A[i]+B[j], and array CD to store all possible values of -C[k]-D[l]. Then we sort AB and CD respectively. Now we only need to find how many pairs of equal values in AB and CD there are. This can be done with O(N^2) time, so the total time complexity is also O(N^2).
Code for Solution 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
public:
intfourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D){
int n = A.size(), ans = 0;
unordered_map<int,int> sum;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
++sum[A[i]+B[j]];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
ans += sum[0-C[i]-D[j]];
return ans;
}
};
Code for Solution 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
classSolution {
public:
intfourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D){