天天看點

【Leetcode350】Intersection of Two Arrays II

Runtime: 4 ms, faster than 99.18% of C++ online submissions for Intersection of Two Arrays II.

Memory Usage: 7.9 MB, less than 100.00% of C++ online submissions for Intersection of Two Arrays II.

跟349題差不多,其實把我349解答中的set替換成multiset就可以了,但是,誠如349題中的分析,set的一個好處是有序,另一個是 unique,這樣就不用先排序再去重了(unique函數隻能去除相鄰的重複,真正的去重前需要先sort)

而這裡,不要求unique,是以不能用set,multiset可以滿足要求,但是如果隻是為了追求有序,sort就可以解決,沒有必要再去花時間和空間去建立新的set了。

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        std::sort(nums1.begin(), nums1.end());
        std::sort(nums2.begin(), nums2.end());
        auto p1 = nums1.begin();
        auto p2 = nums2.begin();
        vector<int> result;
        while(p1 != nums1.end() && p2 != nums2.end()){
            if(*p1 == *p2){
                result.push_back(*p1);
                p1++;
                p2++;
            }else if(*p1 < *p2){
                p1++;

            }else{
                p2++;
            }
        }
        return result;
    }
};