您的位置:首页 > 其它

leetcode.349. Intersection of Two Arrays

2016-05-20 15:59 441 查看
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) {
set<int>s1,s2;
int n1=nums1.size(),n2=nums2.size();
for(int i=0;i<n1;i++) s1.insert(nums1[i]);
for(int i=0;i<n2;i++) s2.insert(nums2[i]);
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(*it1<*it2) it1++;
else it2++;
}
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: