采用一个哈希表存储两个数的和,再遍历另外两个数组的和,time O(n2) space O(n2)
class Solution { public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { int N=A.size(); if(N==0) return 0; int res=0; unordered_map<int,int> h; for(auto a:A){ for(auto b:B){ h[a+b]++; } } for(auto c:C){ for(auto d:D){ auto it=h.find(-c-d); if(it!=h.end()) res+=it->second; } } return res; } };