[LeetCode] Intersection of Two Arrays

349. Intersection of Two Arrays

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> us(begin(nums1), end(nums1));
vector<int> res;
for(auto& x : nums2) {
if(!us.count(x)) continue;
res.push_back(x);
us.erase(x);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/10/PS/LeetCode/intersection-of-two-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.