4 line solution using set_intersection(back_inserter)


  • 0
    R
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        
        vector<int> ans;
        set_intersection(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), back_inserter(ans));
         
        return ans;
    }
    

    Using
    std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(),
    std::back_inserter(v_intersection));
    it takes 6ms.


Log in to reply
 

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