- 描述: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 -2^28 to 2^28 - 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:
2Explanation:
The two tuples are:
- (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
- (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
- 分析:这是一道寻找四个数组中有多少个元素只和为0的题目,首先,暴力解法(4层循环)是行不通的,因为数组元素较多,会浪费很多时间。
- 思路一:直接用map解题,先判断两个数组只和,然后用第三个和第四个数组只和的相反数在前两个和之中寻找,如果找到,给计数器加上匹配的数值。 (579 ms)
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
map<int, int> my_map;
int flag = 0;
for (int i = 0; i < A.size(); i++) {
for (int j = 0; j < B.size(); j++) {
my_map[A[i]+B[j]]++;
}
}
for (int i = 0; i < C.size(); i++) {
for (int j = 0; j < D.size(); j++) {
if (my_map.find(-(C[i] + D[j])) != my_map.end()) {
flag += my_map[-(C[i] + D[j])];
}
}
}
return flag;
}
};
- 思路二:用unordered_map作为容器可以使时间减少一倍。(242 ms)
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> my_map;
int flag = 0;
for (int i = 0; i < A.size(); i++) {
for (int j = 0; j < B.size(); j++) {
my_map[A[i]+B[j]]++;
}
}
for (int i = 0; i < C.size(); i++) {
for (int j = 0; j < D.size(); j++) {
if (my_map.find(-(C[i] + D[j])) != my_map.end()) {
flag += my_map[-(C[i] + D[j])];
}
}
}
return flag;
}
};