four numbers together leetcode 454

 Using a hash table to store two numbers and then traverse and the other two arrays, 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;
    }
};

 

Guess you like

Origin www.cnblogs.com/joelwang/p/10984232.html