Two Sinple C++ solution using sort&unique and hashmap


  • 0
    A

    Solution 1 Sort and Unique

            sort(nums1.begin(),nums1.end());
            sort(nums2.begin(),nums2.end());
            
            auto it1 = unique(nums1.begin(), nums1.end());
            nums1.resize(it1 - nums1.begin());
            
            auto it2 = unique(nums2.begin(), nums2.end());
            nums2.resize(it2 - nums2.begin());
            auto it = set_intersection(nums1.begin(),nums1.end(),nums2.begin(),nums2.end(),nums1.begin());
            nums1.resize(it-nums1.begin());
            return nums1;
    

    Solution 2 Hash

            unordered_map<int, short> h; //hashmap
            vector<int> r; //return vector
            for(auto &i: nums1) 
                if(h[i]==0) h[i]++;
            for(auto &i: nums2) 
                if(h[i]--==1) 
                    r.push_back(i);
            return r;
    

Log in to reply
 

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