您的位置:首页 > 编程语言 > C语言/C++

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;
}
};


针对思考的第一个问题,算法中只要省去排序的步骤就行,第二个问题的话这个算法本身已经很优化了,只要当一个数组扫描到末尾的时候就会结束,针对第三个问题的话,我的看法是换用其他的方法,比如哈希,不需要一次性读入所有的元素,只要一批一批的读统计元素的个数就可以了,然后在进行比较,这边代码就不写了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++