# C++每日一练26-四数相加 II

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

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;
}
}


06-27 121

11-16 210
11-27 30
03-16 32
10-20 1万+
10-10 520
01-10 855
09-30 212
09-16 3156
10-30 700
07-12 1328
07-24 2万+
05-24 31
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客