350. Intersection of Two Arrays II
2016-07-20 10:04
387 查看
题目:Intersection of Two Arrays II
原题链接:https://leetcode.com/problems/intersection-of-two-arrays-ii/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?
给出两个数组,返回这两个数组元素的交集(元素可重复、返回顺序任意)。
思考:如果给定的数组已经有序,怎么优化你的算法?如果第一个数组的大小比第二个小呢?如果第二个数组的元素存储在磁盘上,并且内存限制你不能一次性把所有的元素加载到内存里?
把两个数组排序,然后从头开始同时扫描2个数组,元素相同则输出,元素不同则根据大小关系决定哪个数组的扫描接着往下,代码如下:
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int len1 = nums1.size(), len2 = nums2.size(); vector<int> ans; int i = 0, j = 0; while(i < len1 && j < len2) { if(nums1[i] == nums2[j]) { ans.push_back(nums1[i]); i++,j++; }else if(nums1[i] < nums2[j]) { i++; }else j++; } return ans; } };
针对思考的第一个问题,算法中只要省去排序的步骤就行,第二个问题的话这个算法本身已经很优化了,只要当一个数组扫描到末尾的时候就会结束,针对第三个问题的话,我的看法是换用其他的方法,比如哈希,不需要一次性读入所有的元素,只要一批一批的读统计元素的个数就可以了,然后在进行比较,这边代码就不写了。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解