https://leetcode.com/problems/intersection-of-two-arrays/
https://leetcode.com/problems/intersection-of-two-arrays-ii/
1.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.
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
/*
//another method with set,slow
set<int> s(nums1.begin(), nums1.end()), res;
for (auto a : nums2) {
if (s.count(a)) res.insert(a);
}
return vector<int>(res.begin(), res.end());
*/
//my method,fast
vector<int> res;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int>::iterator iter1=nums1.begin(),iter2=nums2.begin();
for( ; ( iter1!=nums1.end() && iter2!=nums2.end() ); ){
if( *iter1 < *iter2 ){
++iter1;
}else{
if( *iter1 > *iter2 ){
++iter2;
}else{
if( (res.empty())||(res.back()!=*iter1) ){
res.push_back(*iter1);
}
++iter1;
++iter2;
}
}
}
return res;
}
};
2.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.
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
/*
//another method with hash_table, beat 50%
unordered_map<int,int> num;
vector<int> res;
for (auto i : nums1) ++num[i];
for (auto i : nums2) {
if (num[i]-- > 0) res.push_back(i);
}
return res;
*/
//my method, beat 75%
vector<int> res;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int>::iterator iter1=nums1.begin(),iter2=nums2.begin();
for( ; ( iter1!=nums1.end()&&iter2!=nums2.end() ); ){
if( *iter1==*iter2 ){
res.push_back(*iter1);
++iter1;
++iter2;
}else{
if(*iter1<*iter2){
++iter1;
}else{
++iter2;
}
}
}
return res;
}
};