Given the arrays, write a function to compute their intersection.
Notice
Each element of the result should appear as many times as it shows in both arrays.
The result can be on any order.
Example
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Challenge
What if the given array is already sorted? How would optimize your algorithm?
What if Nums1 ' s size is small compared to num2 ' s size? Which algorithm is better?
What if elements of nums2 be stored on disk, and the memory is limited such so you cannot load all elements into the ME Mory at once?
Leetcode on the original topic, see my previous blog intersection of Arrays Ii.
Solution One:
classSolution { Public: /** * @param nums1 an integer array * @param nums2 a integer array * @return an integer array*/Vector<int> Intersection (vector<int>& Nums1, vector<int>&nums2) {Vector<int>Res; Unordered_map<int,int>m; for(auto a:nums1) + +M[a]; for(Auto a:nums2) {if(M[a] >0) {res.push_back (a); --M[a]; } } returnRes; }};
Solution Two:
classSolution { Public: /** * @param nums1 an integer array * @param nums2 a integer array * @return an integer array*/Vector<int> Intersection (vector<int>& Nums1, vector<int>&nums2) {Vector<int>Res; inti =0, j =0; Sort (Nums1.begin (), Nums1.end ()); Sort (Nums2.begin (), Nums2.end ()); while(I < Nums1.size () && J <nums2.size ()) { if(Nums1[i] < Nums2[j]) + +i; Else if(Nums1[i] > Nums2[j]) + +J; Else{res.push_back (nums1[i]); ++i; ++J; } } returnRes; }};
[Lintcode] Intersection of two Arrays II two arrays intersect the second