Simple C++ Solution With Sort and Merge, 6 ms


  • 0
    M
    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            vector<int> result;
            sort(nums1.begin(), nums1.end());
            sort(nums2.begin(), nums2.end());
            int i1 = 0, i2 = 0;
            while (i1 < nums1.size() && i2 < nums2.size()) {
                if (nums1[i1] == nums2[i2]) {
                    if (result.empty() || result.back() != nums1[i1]) result.push_back(nums1[i1]);
                    ++i1; ++i2;
                } else if (nums1[i1] < nums2[i2]) ++i1; else ++i2;
            }
            return result;
        }
    };
    

Log in to reply
 

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