12 ms C++ using hash table


  • 0
    L
    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            vector<int> result;
            unordered_map<int,int> hashmap1;
            //store the elements of nums1 in hashmap1
            for(int k:nums1){
                if(hashmap1.find(k)==hashmap1.end()){
                    hashmap1[k]=1;
                }
            }
            //find the common values and avoid duplicates
            for(int k:nums2){
                if((hashmap1.find(k)!=hashmap1.end())&&(hashmap1[k]==1)){
                    result.push_back(k);
                    hashmap1[k]=0;
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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