mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 09:29:56 +08:00
815 B
815 B
题目地址
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;
}
};