Efficient C++ code. O(1) Space. O(max(nlogn),mlog(m)) time complexity. beats 88.17%


  • 0
    N
    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            vector<int>ans;
            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])
                {
                    int temp=nums1[i];
                    ans.push_back(temp);
                    while(nums1[i]==temp&&i<nums1.size())i++;
                    while(nums2[j]==temp&&j<nums2.size())j++;
                }
                else if(nums1[i]>nums2[j])
                {
                    while(nums1[i]>nums2[j]&&j<nums2.size())j++;
                }
                else 
                {
                    while(nums1[i]<nums2[j]&&i<nums1.size())i++;
                }
            }
            return ans;
        }
    };

Log in to reply
 

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