欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 350. Intersection of Two Arrays II

程序员文章站 2022-07-15 10:46:31
...

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:

LeetCode 350. Intersection of Two Arrays II


相关标签: leetcode hash