O(N) using unordered_map in C++ (easy to understand)


  • 0
    J

    class Solution {
    public:

    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,int> map;
        vector<int> result;
        
        for(int i=0; i < nums1.size(); i++){
            if(map.find(nums1[i]) == map.end()){
                map.insert(pair<int,int>(nums1[i], i));
            }
        }
        
        for(int i=0; i < nums2.size(); i++){
            if(map.find(nums2[i]) != map.end()){
                result.push_back(nums2[i]);
                map.erase(nums2[i]);
            }
        }
        
        return result;
    }
    

    };


Log in to reply
 

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