leetcode: 349. Intersection of Two Arrays
原题链接
我的写法:使用unordered_map
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> ans;
unordered_map<int, bool> mp;
for (int x : nums1) mp[x] = true;
for (int x : nums2)
if (mp[x]) {
ans.push_back(x);
mp[x] = false;
}
return ans;
}
};
还有种写法(使用unordered_set):
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> ans;
unordered_set<int> nums_set(nums1.begin(), nums1.end());
for (int x : nums2)
if (nums_set.find(x) != nums_set.end())
ans.insert(x);
return vector<int> (ans.begin(), ans.end());
}
};