O(n^2) time and O(n^2) space using hash map


  • 0
    P
    class Solution {
    public:
        int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
            int count = 0;
            unordered_map<int, int> mp;
            int n = A.size();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    mp[A[i] + B[j]]++;
                }
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    count += mp[0-C[i]-D[j]];
                }
            }
            return count;        
        }
    };
    

  • 0
    N

    worst case in hashmap in O(n) S your time complexity in worst case is O(n^3)


Log in to reply
 

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