c++ using std::sort


  • 1
    P
    #include <algorithm>
    class Solution {
    public:
        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
            std::sort(nums1.begin(), nums1.end());
            std::sort(nums2.begin(), nums2.end());
            
            vector<int> result;
            for(int i = 0, j = 0; i < nums1.size() && j < nums2.size(); ) {
                if(nums1[i] < nums2[j]) i++;
                else if(nums1[i] > nums2[j]) j++;
                else {
                    result.push_back(nums1[i]);
                    i++;
                    j++;
                }
            }
            return result;
        }
    };
    

  • 0
    Y

    the same of mine
    only 9 ms

    class Solution {
    public:
        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
            sort(nums1.begin(),nums1.end());
            sort(nums2.begin(),nums2.end());
            int n=0,m=0;
            vector<int> result;
            while (n<nums1.size() && m<nums2.size())
            {
                if (nums1[n]<nums2[m]) ++n;
                else if (nums1[n]>nums2[m]) ++m;
                     else
                     {
                         result.push_back(nums1[n]);
                         ++n;
                         ++m;
                     }
            }
            return result;
        }
    };
    

Log in to reply
 

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