给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
为了使问题简单化,所有的 A, B, C, D 具有相同的⻓度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -2^28 到 2^28 - 1
之间,最终结果不会超过 2^31 - 1 。
例如:
输⼊:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
// 遍历当前元素,并在map中寻找是否有匹配的key
auto iter = map.find(target - nums[i]);
if(iter != map.end()) {
return {iter->second, i};
}
// 如果没找到匹配对,就把访问过的元素和下标加⼊到map中
map.insert(pair<int, int>(nums[i], i));
}
return {};
}
};
D = [ 0, 2]
输出:
2
解释:
两个元组如下:
- (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
本题解题步骤:
- ⾸先定义 ⼀个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。
- 遍历⼤A和⼤B数组,统计两个数组元素之和,和出现的次数,放到map中。
- 定义int变量count,⽤来统计 a+b+c+d = 0 出现的次数。
- 在遍历⼤C和⼤D数组,找到如果 0-(c+d) 在map中出现过的话,就⽤count把map中key对应的value也就是出
现次数统计出来。 - 最后返回统计值 count 就可以了
代码展示:
class Solve{public:int sum(vector<int>&A,vector<int>&B,vector<int>&C,vector<int>&D){unordered_map<int ,int>map;for(auto a:A){for(auto b:B){map[a+b]++;}}int cnt=0;for(auto c:C){for(auto d:D){if(map.find(0-(c+d))!=map.end()){cnt+=map[0-(c+d)];}}}return cnt;}
};