题目链接:https://leetcode.cn/problems/intersection-of-two-arrays/
思路如下:
由题目可知,nums1 数组和 nums2 数组中的元素的大小都在
[
0
,
1000
]
[0,1000]
[0,1000],因此可以使用数组来做哈希表。
C++代码如下:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<bool> visited(1010);
vector<int> res;
for (auto& x : nums1) {
visited[x] = true;
}
for (auto& x : nums2) {
if (visited[x]) {
res.push_back(x);
visited[x] = false;
}
}
return res;
}
};