Description:
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
Output:
2
Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
Language: C++
解法一:
题目中一个很重要的信息是数字的range,也就是A, B, C, D的长度分别的在500以内。这个要求我们考虑到算法复杂度。最直接的算法是暴力解法,但是它达到了
O(n4)
O
(
n
4
)
的复杂度,这是计算机承受不了的。即使将一个数组存入map,然后去找,也是
O(n3)
O
(
n
3
)
的复杂度,对于500的大小还是有点承受不了。那么就应该想办法降到
O(n2)
O
(
n
2
)
的复杂度,这个是可以承受的。
思路就是把C和D的组合存入map,并对应的value是频数,代表有多少种同一个key的组合。
Time:
O(n2)
O
(
n
2
)
Space:
O(n2)
O
(
n
2
)
由于map存放的是C+D的组合,而他们分别是
n
n
个元素,组合个数为
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
map<int,int> record;
for(int i = 0; i < C.size(); i++)
for(int j = 0; j < D.size(); j++){
record[C[i]+D[j]]++;
}
int res = 0;
for(int i = 0; i < A.size(); i++)
for(int j = 0; j < B.size(); j++){
if(record.find(-A[i]-B[j])!=record.end())
res+=record[-A[i]-B[j]];//不是res++!应该是当前值所有C+D组合的个数
}
return res;
}
};
算法细节:
特别需要注意的是在A, B找target = 0 - (c+d)的时候,res要加上的是map中当前target的value值,也就是它的频数,而不是仅仅加1,这是因为这说明同一个target的c+d组合有这么多。