1、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.
感觉这个做法十分简单粗暴,就是把两个数组排好顺序,从前到后的比较,相同就放入result,同时后移接着比较,一大一小就后移小的,就酱~
最后把result的重复的清空偷懒用了两个STL函数嘻嘻~~
然鹅效率还可以~~
class Solution{
public:
vector<int> intersection(vector<int> & num1,vector<int> & num2){
vector<int> result;
int s1,s2;
s1=num1.size();
s2=num2.size();
sort(num1.begin(),num1.end());
sort(num2.begin(),num2.end());
for(int i = 0,j = 0;i < s1 && j < s2;){
if(num1[i]==num2[j]){
result.push_back(num1[i]);
i++;
j++;
}
else if(num1[i]>num2[j])
j++;
else
i++;
}
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
1、
iterator erase (const_iterator position);//删一个
iterator erase (const_iterator first, const_iterator last);//删一段
Removes from the vector either a single element (position) or a range of elements ([first,last)).
2、
ForwardIterator unique (ForwardIterator first, ForwardIterator last);
返回An iterator to the element that follows the last element not removed.
unique只是把重复的元素放到容器的后面,而它本身会返回一个迭代器,只向这些元素的开始部分,举个栗子~
int myints[] = {10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10
std::vector<int> myvector (myints,myints+9);
std::vector<int>::iterator it;
it = std::unique (myvector.begin(), myvector.end()); // 10 20 30 20 10
2、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.
与上面题唯一的区别就是不用去重,就是把倒数第二句删掉就好了~
class Solution{
public:
vector<int> intersect(vector<int> & num1,vector<int> & num2){
vector<int> result;
int s1,s2;
s1=num1.size();
s2=num2.size();
sort(num1.begin(),num1.end());
sort(num2.begin(),num2.end());
for(int i = 0,j = 0;i < s1 && j < s2;){
if(num1[i]==num2[j]){
result.push_back(num1[i]);
i++;
j++;
}
else if(num1[i]>num2[j])
j++;
else
i++;
}
return result;
}
};