leetcode-master/problems/0350.两个数组的交集II.md

37 lines
1.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
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;
}
};
```
> 更过算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。