LeetCode 350. Intersection of Two Arrays II

题意:求两个数组的相交。要求相同的元素不合并,全部输出。

solution:hash。首先记录第一个数组的元素出现情况count,然后遍历第二个数组,每次先将相应的hash值-1,如果此时hash值仍大于等于0。这么做是因为交集中元素的最大出现次数也不会大于第一个数组的出现次数。

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> hash; // num - count
        vector<int> res;
        for ( auto n : nums1 ) {
            hash[n]++;
        }
        for ( auto n : nums2 ) {
            hash[n]--;
            if ( hash[n] > 0 || hash[n] == 0 ) {
                res.push_back(n);
            }
        }
        return res;
    }
};

submission:



猜你喜欢

转载自blog.csdn.net/jack_ricky/article/details/79379705