Share C++ code, sort and compare O(n)


  • 0
    W
    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            sort(nums1.begin(),nums1.end());
            sort(nums2.begin(),nums2.end());
            vector<int> inter;
            int n=nums1.size(); int m=nums2.size();
            int i=0; int j=0;
            while(i<n&&j<m){
                if(nums1[i]<nums2[j])i++;
                else if(nums1[i]>nums2[j]) j++;
                else if(inter.size()==0 ||nums1[i]!=inter[inter.size()-1]){inter.push_back(nums1[i]);i++;j++;}
                else{i++;j++;}
            }return inter;
        }
    };

Log in to reply
 

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