Intersection Of Array

Intersection Of Array

题目描述:

给定两个数组,找到两个数组中数字的交集

例子:

LeetCode349

解题思路:

我们首先对第一个数组进行构建哈希表,然后遍历第二个数组,如果数字在哈希表中,将其保存到结果中,并将该值从哈希表中删除即可

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> hash;
vector<int> res;
for (int i = 0; i < nums1.size(); i++){
if (hash.find(nums1[i]) == hash.end()){
hash.insert({nums1[i]});
//对第一个数组构建哈希表
}
}
for (int j = 0; j < nums2.size(); j++){
if (hash.find(nums2[j]) != hash.end()){
hash.erase(nums2[j]);
res.push_back(nums2[j]);
//遍历第二个数组中的数
}
}
return res;
}
};