Simple while loop solution C++ 12ms.


  • 0
    S
    class Solution {
    public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> output;
        //Sort the Vectors.
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        
        auto it1 = nums1.begin(), it2 = nums2.begin();
        while(it1 != nums1.end() && it2 != nums2.end()) {
            if(*it1 == *it2) {
                output.push_back(*it1);
                it1++;
                it2++;
            } else if(*it1 > *it2) {
                it2++;
            } else {
                it1++;
            }
        }
        return output;
    }
    };

Log in to reply
 

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