题目描述
给定两个数组,请写一个函数计算它们的交集。
示例
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2],
返回 [2, 2].
思路
首先先将nums1存入哈希表中,然后遍历nums2,对于每个数 x,如果 x 出现在哈希表中,则将 x 输出,且从哈希表中删除一个 x。
map代码
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int>a;
map<int,int>hash;
for(auto x:nums1)
hash[x]++;
for(auto y:nums2)
if(hash[y]>0)//这里不能用hash.count(),map.count(Key)返回值为1或者0,1返回存在,0返回不存在,只要一个数x被标记,即使hash[x]=0,那么hash.count(x)也是等于1的。
{
a.push_back(y);
hash[y]--;
}
return a;
}
};
set 代码
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_multiset<int> S;
vector<int> res;
for (int x : nums1) S.insert(x);
for (int x : nums2)
if (S.count(x))
{
res.push_back(x);
S.erase(S.find(x));
}
return res;
}
};