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),大神的解法還沒看,看後再更新。