题目:
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 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?
给定两个数组,计算两个数组的交叉重叠部分。
note:
1、结果集中的元素出现的次数应该跟其在两个数组中出现的次数一样;
2、结果集可以按任意顺序;
Follow up:
1、如果给定的数组已经排好序了,如果优化算法?
2、如果第一个数组小于第二个数组,如何优化算法?
3、如果第二个数组存储在硬盘上,而内存有限不能一次将第二个数组全部加载到内存中,如果优化算法;
思路一:
借助map实现,保存一个数组到map中,之后与下一个数组进行对比。
代码:12ms
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> mapping; vector<int> result; for(int i=0; i<nums1.size(); i++){ mapping[nums1[i]]++; } for(int i=0; i<nums2.size(); i++){ if(mapping.find(nums2[i])!=mapping.end() && --mapping[nums2[i]]>=0){ result.push_back(nums2[i]); } } return result; } };思路二:
先将两个数组排序,之后直接将两个数组逐个对比。
代码:8ms
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int m = nums1.size(); int n = nums2.size(); int c1 = 0; int c2 = 0; vector<int> result; while(c1 < m && c2 < n){ if(nums1[c1]==nums2[c2]){ result.push_back(nums1[c1]); c1++; c2++; }else if(nums1[c1] > nums2[c2]){ c2++; }else{ c1++; } } return result; } };