Share my C++ solution which using the sort function sort in STL


  • 0
    E

    My solution is simple:
    step 1. sort the input two vectors;
    step 2. compare ith element in nums1 and jth in nums2.
    step 3. filter the same elements in the same vector.

    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {

        int nums1_size = nums1.size();
        int nums2_size = nums2.size();
        
        vector<int> res;
        if(nums1_size == 0 || nums2_size == 0)
            return res;
            
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        
        for(int i=0, j =0; i< nums1.size() && j < nums2.size();)
        {
            if(nums1[i] == nums2[j])
            {
                res.push_back(nums1[i]);
                ++i;
                ++j;
                while(i < nums1.size() && nums1[i] == nums1[i-1])
                    ++i;
                while( j < nums2.size() && nums2[j] == nums2[j-1])
                    ++j;
            }
            else if(nums1[i] < nums2[j])
                ++i;
            else 
                ++j;
        }
        return res;
    }

Log in to reply
 

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