350. Intersection of Two Arrays II (Leetcode)

PHOTO EMBED

Wed Oct 06 2021 08:11:28 GMT+0000 (UTC)

Saved by @Sakshamkashyap7 #c++

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,int>mp;
        vector<int> ans;
        for(int i = 0; i < nums2.size(); ++i)   mp[nums2[i]]++;
    
        for(int i = 0; i < nums1.size(); ++i)   { 
            if(mp[nums1[i]] > 0)    {
                mp[nums1[i]]--;
                ans.push_back(nums1[i]);
            }
        }
        return ans;
    }
};
content_copyCOPY

Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]

https://leetcode.com/problems/intersection-of-two-arrays-ii/submissions/