LeetCode 350. Intersection of Two Arrays II
2016-07-12 14:38
295 查看
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
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?
这个题目根据Follow up的条件,还是用map比较好。
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?
这个题目根据Follow up的条件,还是用map比较好。
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> nums3; map<int, int> m; int len1 = nums1.size(), len2 = nums2.size(); int i; for(i = 0; i < len1; i ++){ m[nums1[i]] ++; } map<int, int>::iterator it; for(i = 0; i < len2; i ++){ it = m.find(nums2[i]); if(it != m.end() && (*it).second != 0){ (*it).second --; nums3.push_back(nums2[i]); } } return nums3; } };
相关文章推荐
- Java中的锁
- 【bzoj4552】【Tjoi2016&Heoi2016】【NOIP2016模拟7.12】排序
- Reverse Bits
- 7.12 noip2103提高组复赛day2
- RabbitMQ消息队列(二):”Hello, World“
- Java常用代码工具类相关
- Trilateration三边测量定位算法
- 刚刚提取了金山毒霸的[垃圾清理] 和 [隐私清理], 分享方法,大家可以自己试一下
- Google App Engine的app.yaml详细说明
- Android绘制音乐播放器示波器
- java I/O流详解
- java加载properties文件的六种基本方式
- 数值的整数次方代码实现
- {小结}2016.07.12【初中部 NOIP提高组 】模拟赛B
- Ubuntu 上进行VNCserver的搭建
- C语言入门(十七)指针概念
- 生成1到300个数字的方法
- Java 中的锁——Lock接口
- Objective-C Runtime
- MyBatis学习4---使用MyBatis_Generator生成Dto、Dao、Mapping