C++ using sort and two pointer


  • 1
    I

    Sort the two vectors first, then using two pointers to find the unique common value.

    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            vector<int>res;
            sort(nums1.begin(),nums1.end());
            sort(nums2.begin(),nums2.end());
            auto n1=nums1.begin();
            auto n2=nums2.begin();
            while(n1!=nums1.end()&&n2!=nums2.end()){
                if(*n1>*n2){
                    n2++;
                }else if(*n1<*n2){
                    n1++;
                }else{
                    if(res.size()&&res.back()==*n1){
                        while(*n1==res.back())n1++;
                        while(*n2==res.back())n2++;
                    }else{
                        res.push_back(*n1);
                        n1++,n2++;
                    }
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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