1.题目描述
Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 求两个数组的交集。与题目349. Intersection of Two Arrays类似。此题需要保留重复。
2.分析
(1)重复的元素 (2)重复的次数 用unordered_map来实现一个字典,记录元素出现的次数
3.代码
vector<int> intersect(
vector<int>& nums1,
vector<int>& nums2) {
unordered_map<int, int> dict_1;
for (
int n : nums1)
dict_1[n]++;
vector<int> result;
for (
int n : nums2) {
if (dict_1[n] >
0) {
--dict_1[n];
result.push_back(n);
}
}
return result;
}