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.
使用unordered_map,时间复杂度O(n):
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
const int sz1 = nums1.size();
const int sz2 = nums2.size();
unordered_map<int, int> umap;
for(int i=0; i<sz1; ++i)
umap[nums1[i]]++;
for(int i=0; i<sz2; ++i){
if(umap[nums2[i]] != 0){
res.push_back(nums2[i]);
umap[nums2[i]] = 0;
}
}
return res;
}
};
另一道题是:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
同理:
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
unordered_map<int, int> umap;
for(auto i : nums1)
umap[i]++;
for(auto i : nums2){
if(umap[i] != 0){
res.push_back(i);
umap[i]--;
}
}
return res;
}
};
本文介绍两种数组交集问题的解决方案,一种确保结果中每个元素唯一,另一种则保持两数组中重复元素出现次数一致。通过使用unordered_map实现O(n)的时间复杂度。


被折叠的 条评论
为什么被折叠?



