Easy Solution using two pointers


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

Log in to reply
 

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