350. Intersection of Two Arrays II
2016-05-21 16:19
363 查看
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 num2'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?
【思路】用两个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 num2'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?
【思路】用两个map分别存储两个数组中的元素,将相同元素,次数较少的存入结果中。
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> inter; if(nums1.empty()||nums2.empty()) return inter; int i = 0, j = 0; int l1 = nums1.size(), l2 = nums2.size(); map<int,int>m1; map<int,int>m2; for(; i < l1; i++) { m1[nums1[i]]++; } for(; j < l2; ++j) { m2[nums2[j]]++; } map<int, int>::iterator it2 = m2.begin(); while(it2!=m2.end()) { map<int, int>::iterator it1 = m1.find(it2->first); if(it1!=m1.end()) { int tmp = (it1->second)> (it2->second)? (it2->second):(it1->second); for(int k = 0; k < tmp ; k++) { inter.push_back(it1->first); } } ++it2; } return inter; } };
相关文章推荐
- 迷之1025 反转链表
- 音频相关的基本知识
- Python——脚本(calculator)
- Think In Java
- 回到顶部按钮
- Huffman算法
- 动态存储实现通讯录
- UEditor路径配置
- 使用spring4.1 hibernate4.1 struts2.1 Tomcat8 部署项目异常解决方法
- 跟我一起学习MySQL技术内幕(第五版):(第三章学习日记9)
- 常用的Mysql数据库操作语句大全
- 树的直径
- Android ViewPager使用详解
- Axure 图片轮播(广告通栏图片自动播放效果)
- SM2算法第二十六篇:openSSL 中BIGNUM的使用记录
- 电容的等效串联电阻 ESR
- bzoj 1004: [HNOI2008]Cards(置换)
- 2016年华为网络技术精英大赛复赛试题
- 自动完成文本输入框提示,下拉列表,发送状态栏消息,消息提醒
- RESTfulClient