6-liner O(N1+N2) time, O(min(N1, N2)) space


  • 0

    Make sure to always check key existence in hash map before [] operator to avoid unnecessary memory usage.

        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) 
        {
            if (nums1.size() > nums2.size()) swap(nums1, nums2); // make sure nums1 is the shorter array
            
            unordered_map<int, int> fre1; // make frequency map for nums1
            for (int x : nums1) ++fre1[x];
            
            vector<int> intersections; // check x existence to avoid unnecessary memory usage
            for (int x : nums2) if (fre1.count(x) && --fre1[x] >= 0) intersections.push_back(x);
            return intersections;
        }
    

Log in to reply
 

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