A 12ms Easy-understand Unordered Map C++ Solution


  • 0
    Y
    class Solution {
    public:
        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
            vector<int> ans = {};
            if(nums1.size() == 0 && nums2.size() == 0) return ans;
            
            unordered_map<int,int> map;
            
            for(int i = 0; i < nums1.size(); i++) map[nums1[i]]++;
            
            for(int j = 0; j < nums2.size(); j++) {
                if(map.find(nums2[j]) != map.end() && map.find(nums2[j])->second > 0) {
                    ans.push_back(nums2[j]);
                    map[nums2[j]]--;
                }
            }
            
            return ans;
        }
    };

Log in to reply
 

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