# leetcode349&350

150人阅读 评论(0)

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.

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);

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;
}
};

个人资料
等级：
访问量： 9818
积分： 667
排名： 7万+
文章存档