Simple C++ Solution, O(m+n) time using a map


  • 0
    F
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2){
            vector<int> intersection;
            map<int, int> mymap;
            
            for(int i = 0; i < nums1.size(); i++){
                mymap[nums1[i]]++;
            }
            
            for(int i = 0; i < nums2.size(); i++){
                if(mymap[nums2[i]]){
                    intersection.push_back(nums2[i]);
                    mymap[nums2[i]]--;
                }
            }
            return intersection;
      }
    

    The idea is simple, map all values increment for each one. Iterating through the second array, decrement the count for that key and push it back if the count is not zero.


Log in to reply
 

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