Files
leetcode-master/problems/0350.两个数组的交集II.md
youngyangyang04 1c6a050210 Update
2020-07-09 09:14:58 +08:00

1.1 KiB
Raw Blame History

题目地址

https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/

思路

这道题目看上去和349两个数组的交集题目描述是一样的其实这两道题解法相差还是很大的编号349题目结果是去重的

而本题才求的真正的交集求这两个集合元素的交集需要掌握另一个哈希数据结构unordered_map

代码

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        unordered_map<int, int> map;
        for (int num : nums1) {
            map[num]++;
        }
        for (int num : nums2) {
            if (map[num] > 0) {
                result.push_back(num);
                map[num]--;
            }
        }
        return result;
    }
};

笔者在先后在腾讯和百度从事技术研发多年利用工作之余重刷leetcode本文 GitHubhttps://github.com/youngyangyang04/leetcode-master 已经收录欢迎starfork共同学习一起进步。