題目介紹
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].Note:
Each element in the result must be unique.
The result can be in any order.
C++ 解法 using unordered_set
unordered庫提供兩個散列集合類unordered_set和unordered_multiset,STLport也提供hash_set和hash_multiset,它們的接口,用法與stl裏的標準關聯容器set/multiset相同,只是內部使用散列表代替了二叉樹實現,因此查找複雜度由數降爲常數。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> m(nums1.begin(), nums1.end());
vector<int> res;
for (auto a : nums2)
if (m.count(a)) {
res.push_back(a);
m.erase(a);
}
return res;
}
};