8ms C++ solution


  • 0
    S

    class Solution {

    public:
        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
            vector<int>result;
            sort(nums1.begin(),nums1.end());
            sort(nums2.begin(),nums2.end());
            vector<int>::iterator iter1=nums1.begin(),iter2=nums2.begin();
            while(iter1!=nums1.end()&&iter2!=nums2.end())
            {
                while(iter1!=nums1.end()&&iter2!=nums2.end()&&*iter1==*iter2)
                {
                    result.push_back(*iter1);
                    ++iter1;
                    ++iter2;
                }
                while(iter2!=nums2.end()&&*iter1>*iter2)++iter2;
                while(iter1!=nums1.end()&&*iter1<*iter2)++iter1;
            }
            return result;
        }
    };

  • 0

    Your solution looks good, time complexity is O(n * logn).
    There is another O(n) solution with hash map.


Log in to reply
 

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