454.4Sum II

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {

        assert( A.size() == B.size() && B.size() == C.size() && C.size() == D.size() );
        unordered_map<int,int> hashtable;
        for( int i = 0 ; i < C.size() ; i ++ )
            for( int j = 0 ; j < D.size() ; j ++ )
                hashtable[C[i]+D[j]] += 1;

        int res = 0;
        for( int i = 0 ; i < A.size() ; i ++ )
            for( int j = 0 ; j < B.size() ; j ++ )
                if( hashtable.find(-A[i]-B[j]) != hashtable.end() )
                    res += hashtable[-A[i]-B[j]];

        return res;
    }
};
class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {

        unordered_map<int,int> hashtable1;
        unordered_map<int,int> hashtable2;

        for( int i = 0 ; i < A.size() ; i ++ )
            for( int j = 0 ; j < B.size() ; j ++ )
                hashtable1[A[i]+B[j]] += 1;

        for( int i = 0 ; i < C.size() ; i ++ )
            for( int j = 0 ; j < D.size() ; j ++ )
                hashtable2[C[i]+D[j]] += 1;

        int res = 0;
        for( unordered_map<int,int>::iterator iter = hashtable1.begin() ; iter != hashtable1.end() ; iter ++ )
            if( hashtable2.find(-(iter->first)) != hashtable2.end() )
                res += iter->second * hashtable2[-(iter->first)];

        return res;
    }
};

results matching ""

    No results matching ""