LeetCode "454. 4Sum II"

Split it into 2 group of arrays, 2 arrays in each group. Then use hashmap.

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int n = A.size(); if(!n) return 0;
        
        int ret = 0;
        unordered_map<int, unsigned> hm1, hm2;
        for(int i = 0; i < n; i ++)
        for(int j = 0; j < n; j ++)
            hm1[A[i] + B[j]] ++, hm2[C[i] + D[j]] ++;
        
        for(auto &kv: hm1)
            if(hm2.find(-kv.first) != hm2.end())
                ret += kv.second * hm2[-kv.first];
        
        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/6353622.html