C++ O(n^2) solution with unordered_map


  • 0
    X
    class Solution {
    public:
        int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
            if (0 == A.size() || 0 == B.size() || 0 == C.size() || 0 == D.size()) return 0;
            
            unordered_map<int, int> mpAB;
            
            for(int i = 0; i < A.size(); i++) {
                for(int j = 0; j < B.size(); j++) {
                    mpAB[A[i] + B[j]]++;
                }
            }
            
            int result = 0;
            for(int i = 0; i < C.size(); i++) {
                for(int j = 0; j < D.size(); j++) {
                    auto itAB = mpAB.find(-(C[i]+D[j]));
                    if (mpAB.end() != itAB) result += itAB->second;
                }
            }
            
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.