四数相加 II
给定四个包含整数的数组列表 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 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。
例如:
输入: A = [ 1, 2] B = [-2,-1] C = [-1, 2] 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum-ii
整体思路
利用前两个数相加的结果构建哈希表并且记录重复的元素的次数,通过哈希表来判断后两个数的负数与key相加结果是否等于0,记录元素次数总和即可
C++代码:
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> mapAB;
int ret = 0;
for (int& n1 : A) {
for (int& n2 : B) {//构建哈希表
if (mapAB.find(n1 + n2) == mapAB.end()) {
mapAB[n1 + n2] = 1;
}
else {
mapAB[n1 + n2]++;
}
}
}
for (int& n3 : C) {
for (int& n4 : D) {
if (mapAB.find(-n3-n4) != mapAB.end()) {//查询是否能存在相加为0的key
ret += mapAB[-n3 - n4];
}
}
}
return ret;
}
};
JAVA代码
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int ret=0;
Map<Integer,Integer> mapAB=new HashMap<Integer, Integer>();
for(int n1:A){
for(int n2:B){
mapAB.put(n1+n2,mapAB.getOrDefault(n1 + n2, 0) + 1);
}
}
for (int n3 : C) {
for (int n4 : D) {
if (mapAB.containsKey(-n3 - n4)) {
ret += mapAB.get(-n3 - n4);
}
}
}
return ret;
}
}
复杂度分析
时间复杂度: O(n^2) n为数组的长度
空间复杂度:O(n^2)