问题描述
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.
思路分析
找到两个数组重叠的部分,也就是两个数组相同的元素有哪些。
首先将两个数组排序,然后用两个指针分别遍历两个数组。两个指针的值相同时,在result为空或与result最后一个元素不同的情况下加入result;如果那个指针的值小(因为排序过了)就向前移动,直到一个数组被遍历完。
代码
class Solution {
public:
vector<int> intersection(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]){
if (result.empty() || nums1[p1] != result.back())
result.push_back(nums1[p1]);
p1++;
p2++;
}
else{
if (nums1[p1] < nums2[p2])
p1++;
else
p2++;
}
}
return result;
}
};
时间复杂度:
O(nlogn)
空间复杂度:
O(n)
反思
使用unordered_set,可以让时间复杂度降低到 O(n) 。将nums1数组存入set,然后再查找nums2中有没有元素在set中,有的话就加入res,并且erase掉这个相同元素。
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;
}
};
时间复杂度:
O(n)
空间复杂度:
O(n)