Intersection of Two Arrays
题目:
Given two arrays, write a function to compute their intersection.
Each element in the result must be unique.
The result can be in any order.
分析:
因为题目要求,结果只保存unique元素,所以选用unordered_set
如果要求保存所有元素,则选用unordered_map
用提高班的方法来说,如果数组一个很大,不能读入Memory,则把小的数组sort好,然后遍历大数组,用每一个元素在小数组中做binary search。
解法:
class Solution {
public:
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
// Write your code here
unordered_set<int> hash;
vector<int> res;
for (int i = 0; i < nums1.size(); i++) {
hash.insert(nums1[i]);
}
for (int i = 0; i < nums2.size(); i++) {
if (hash.find(nums2[i]) != hash.end() ) {
res.push_back(nums2[i]);
hash.erase(nums2[i]);
}
}
return res;
}
};