LeetCode349. Intersection of Two Arrays
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.
题目是求两个数组的交集,交集不能有重复元素,即求两个数组都存在的数字
思路:
题目要求交集没有重复元素,可以先对两个数组进行去重,考虑到要比较两个数组元素的大小,可以将两个数组填充到set容器中,set容器可以自动去重,自动排序,对于排序好的数组,设置两个指针分别从头遍历,若指针位置两个数字相同,则添加到结果数组,两个指针位置向后移动,若不相等,指向小的那个指针向后移动:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> s1(nums1.begin(), nums1.end());
set<int> s2(nums2.begin(), nums2.end());
vector<int> res;
set<int>::iterator it1 = s1.begin(), it2 = s2.begin();
while (it1 != s1.end() && it2 != s2.end()){
if (*it1 == *it2){
res.push_back(*it1);
it1++;
it2++;
}
else if (*it2 > *it1) it1++;
else it2++;
}
return res;
}
};
Leetcode 350 Intersection of Two Arrays II
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.
这题和上题的不同之处在于结果要求将交集的所有元素都添加到结果中,可以有重复元素,解法和上题相似,只要去掉去重的步骤即可,所以可以使用sort将两个数组排序,在进行交集查询:
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
vector<int> res;
vector<int>::iterator it1 = nums1.begin(),it2 = nums2.begin();
while(it1!=nums1.end()&&it2!=nums2.end()){
if(*it1 == *it2){
res.push_back(*it1);
it1++;
it2++;
}
else if(*it1>*it2) it2++;
else it1++;
}
return res;
}
};
这种解法的空间复杂度O(n+m),大神的解法还没看,看后再更新。