Intersection of Two Arrays II

Intersection of Two Arrays II

题目描述:

给定两个数组,要求返回这两个数组之间的交集(重复元素也包括)。

例子:

具体描述见LeetCode350

解题思路:

对第一个数组构建哈希表,key为字符,value为出现的次数;然后遍历第二个字符串,如果遍历过程中该字符出现在哈希表中且出现的次数不为0,则将其保存到结果中,并且将哈希表中该字符出现的数量减一即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
map<int, int>hash;
vector<int> res;
for (int i = 0; i < nums1.size(); i++){
if (hash.find(nums1[i]) == hash.end()){
hash.insert({nums1[i], 1});
}else{
hash[nums1[i]]++;
}
}//构建第一个数组的哈希表
for (int j = 0; j < nums2.size(); j++){
if (hash.find(nums2[j]) != hash.end() && hash[nums2[j]] != 0){
res.push_back(nums2[j]);
hash[nums2[j]]--;
//如果出现在哈希表中,我们保存其到结果中并且将出现的次数减一
}
}
return res;
}
};