问题描述
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.
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?
思路分析
找到两个数组重叠的部分,也就是两个数组相同的元素有哪些,并且有一个算一个。
额,没想到上一次的代码可以直接复用,去掉判断无脑入vector就可以了。
首先将两个数组排序,然后用两个指针分别遍历两个数组。两个指针的值相同时,在result为空或与result最后一个元素不同的情况下加入result;如果那个指针的值小(因为排序过了)就向前移动,直到一个数组被遍历完。
代码
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int> result;
int p1 = 0, p2 = 0;
while (p1 < nums1.size() && p2 < nums2.size()){
if (nums1[p1] == nums2[p2]){
result.push_back(nums1[p1]);
p1++;
p2++;
}
else{
if (nums1[p1] < nums2[p2])
p1++;
else
p2++;
}
}
return result;
}
};
时间复杂度:
O(nlogn+mlogm)
空间复杂度:
O(m+n)
反思
关于follow up3,如何在内存不足的情况下进行比对。答案是hash table 和 sort。
If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections.
If both nums1 and nums2 are so huge that neither fit into the memory, sort them individually (external sort), then read 2 elements from each array at a time in memory, record intersections.
hast table解法:
建立nums1的hash table,每出现一个数,就将其dict位置+1;然后遍历nums2,与字典进行比对,若是在字典中有这个数,并且出现的次数大于0,就将它存入结果几次。
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> dict;
vector<int> res;
for(int i = 0; i < (int)nums1.size(); i++) {
dict[nums1[i]]++;
}
for(int i = 0; i < (int)nums2.size(); i++){
if(dict.find(nums2[i]) != dict.end() && --dict[nums2[i]] >= 0)
res.push_back(nums2[i]);
}
return res;
}
};