题目来源
四个数组,每个数组取一个元素,求和为target的种数。
划分为两块,用哈希,代码如下:
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
int n1 = A.size(), n2 = B.size(), n3 = C.size(), n4 = D.size();
unordered_map<int, int> mapAB, mapCD;
for (int i=0; i<n1; i++)
for (int j=0; j<n2; j++) {
mapAB[A[i]+B[j]]++;
}
int res = 0;
for (int i=0; i<n3; i++)
for (int j=0; j<n4; j++) {
mapCD[C[i]+D[j]]++;
if (mapAB.count(0-(C[i]+D[j])) != 0)
res += mapAB[0-(C[i]+D[j])];
}
return res;
}
};