Leetcode 454 Solution

This article provides solution to leetcode question 454 (4sum-ii)

https://leetcode.com/problems/4sum-ii

Solution

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

        for (auto it1 = A.begin(); it1 != A.end(); it1++)
            for (auto it2 = B.begin(); it2 != B.end(); it2++)
                m1[*it1 + *it2]++;

        for (auto it1 = C.begin(); it1 != C.end(); it1++)
            for (auto it2 = D.begin(); it2 != D.end(); it2++)
                m2[*it1 + *it2]++;

        int total = 0;
        for (auto it = m1.begin(); it != m1.end(); it++)
        {
            total += it->second * m2[-it->first];
        }

        return total;
    }
};