LeetCode 349. Intersection of Two Arrays
2016-06-16 11:29
295 查看
问题描述:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
AC代码:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
vector<int> res;
set<int>s1(nums1.begin(),nums1.end());
set<int>s2(nums2.begin(),nums2.end());
set<int>::iterator it1 = s1.begin();
set<int>::iterator 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;
}这里简要介绍一下set,个人用的比较少,对其理解不深,本题用到的set的以下几个特性:
1.set中的元素都是唯一的,你向同一个set插入同一个元素多次,它只会保存一个。
2.set中的元素值是有序的,比如依次插入 5 6 3 2 7 ,迭代器从头打印,依次打印 2 3 5 6 7,自动排序了。
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
[1, 2, 2, 1], nums2 =
[2, 2], return
[2].
AC代码:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
vector<int> res;
set<int>s1(nums1.begin(),nums1.end());
set<int>s2(nums2.begin(),nums2.end());
set<int>::iterator it1 = s1.begin();
set<int>::iterator 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;
}这里简要介绍一下set,个人用的比较少,对其理解不深,本题用到的set的以下几个特性:
1.set中的元素都是唯一的,你向同一个set插入同一个元素多次,它只会保存一个。
2.set中的元素值是有序的,比如依次插入 5 6 3 2 7 ,迭代器从头打印,依次打印 2 3 5 6 7,自动排序了。
相关文章推荐
- 专题四 Problem D
- iframe 使用
- jenkins创建任务流程
- Android Studio快捷键大全,ctrl+F来搜索
- 如何升级cocos2d-x来支持ipv6以及socket怎么支持ipv6
- 如来
- ORACLE 创建视图时,提示用户权限不足
- qualcomm camera 学习笔记
- Xutils3的使用
- 基本类型转换成NSNumber类型
- 企业家要有赢得市场的激情
- 发一张你认为很漂亮的美女照片?
- 数据结构问题汇总
- &&和&,||和|的区别
- oracle数据库
- GridView的常用属性
- oracle执行计划小结
- oracle 将不同数据合并成一条行数据
- DataType vs ContentType in jquery ajax [duplicate] 数据类型
- 文本分类中的特征选择