Share my C++ solution using sort,easy to understand


  • 0
    V
    class Solution {
    public:
        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
            vector<int> ret;
            int len1 = nums1.size();
            int len2 = nums2.size();
            vector<int>::iterator k1 = nums1.begin();
            vector<int>::iterator k2 = nums2.begin();
            
            if (len1 == 0 || len2 == 0)
                return ret;
            
            sort(nums1.begin(), nums1.end());
            sort(nums2.begin(), nums2.end());
            
            while (k1 != nums1.end() && k2 != nums2.end())
            {
                if (*k1 == *k2)
                {
                    ret.push_back(*k1);
                    k1++;
                    k2++;
                }
                else if (*k1 < *k2)
                    k1++;
                else
                    k2++;
            }
            
            return ret;
        }
    };

Log in to reply
 

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