问题描述:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2,
2]
, return [2]
.
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,自动排序了。