【一天一道LeetCode】#350. Intersection of Two Arrays II
2016-07-13 21:19
447 查看
一天一道LeetCode
(一)题目
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; } };
相关文章推荐
- 【一天一道LeetCode】#350. Intersection of Two Arrays II
- c3p0 config
- RecylerView 的应用
- LeetCode 345. Reverse Vowels of a String
- Python 连接数据库&切割字符串
- 【一天一道LeetCode】#169. Majority Element
- 【一天一道LeetCode】#217. Contains Duplicate
- 【一天一道LeetCode】#217. Contains Duplicate
- 【一天一道LeetCode】#169. Majority Element
- 关于动态数据
- Android学习——自定义Dialog
- Cocos2d-x 图像渲染和动画——3.0坐标系详解
- 带头结点的单链表head为空的判定条件---腾讯2014研发笔试卷
- iOS edgesForExtendedLayout约束(navigationBar遇约束所有元素上偏移问题)
- swust1739: 魔术球问题
- 【一天一道LeetCode】#171. Excel Sheet Column Number
- 【一天一道LeetCode】#242. Valid Anagram
- 【一天一道LeetCode】#242. Valid Anagram
- 【一天一道LeetCode】#171. Excel Sheet Column Number
- .NET微信自定义分享标题、缩略图、超链接及描述的设置方法