您的位置:首页 > 其它

【一天一道LeetCode】#350. Intersection of Two Arrays II

2016-07-13 21:19 447 查看

一天一道LeetCode


本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处



(一)题目


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.

Follow up:

What if the given array is already sorted? How would you optimize your algorithm?

What if nums1’s size is small compared to nums2’s size? Which algorithm is better?

What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?



(二)解题

题目大意:找两个数组的交集,数组中有重复的数。

题目思路:【一天一道LeetCode】#349. Intersection of Two Arrays与上题差不多,只不过这道题不需要考虑去重的问题,所以,去掉重复检测那段就行。

class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> ret;
if(nums1.empty()||nums2.empty()) return ret;
sort(nums1.begin(),nums1.end());//首先对两个数组排序
sort(nums2.begin(),nums2.end());
auto iter1 = nums1.begin();
auto iter2 = nums2.begin();
auto end1 = nums1.end();
auto end2 = nums2.end();
while(iter1 != end1&&iter2!=end2)//其中一个遍历完就退出
{
if(*iter1<*iter2){//*iter2大就把iter1往后找
++iter1;
}
else if(*iter1>*iter2){//*iter1大就把iter2往后找
++iter2;
}
else {//找到了交集
ret.push_back(*iter1);//存储交集
++iter1;
++iter2;
}
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: