Given the arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
- Each element of the result should appear as many times as it shows in both arrays.
- The result can be on any order.
Follow up:
- 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 in To the memory at once?
The problem was the extension of the previous intersection of two arrays, except that the question allowed us to return the duplicate numbers and to return as much as possible, before the problem was that there were repeated numbers returning only one line. So this problem we use a hash table to establish the mapping between the characters in the NUMS1 and the number of occurrences, and then iterate through the NUMS2 array, if the current character is greater than 0 in the hash table, then add this character to the result res, and then the corresponding value of the Hashtable is reduced by 1, see the code below:
Solution One:
classSolution { Public: Vector<int> Intersect (vector<int>& Nums1, vector<int>&nums2) {Unordered_map<int,int>m; Vector<int>Res; for(auto a:nums1) + +M[a]; for(Auto a:nums2) {if(m[a]-->0) Res.push_back (a); } returnRes; }};
Another way to do this is to sort two arrays first, then use two pointers to point to the starting position of two arrays, if two pointers are equal, the two pointers are increased by 1, and if the first pointer is large, the second pointer is increased by 1 and vice versa, see the code below:
Solution Two:
classSolution { Public: Vector<int> Intersect (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]) {Res.push_back (nums1[i]); ++i; ++J; } Else if(Nums1[i] >Nums2[j]) { ++J; } Else { ++i; } } returnRes; }};
Similar topics:
Intersection of Arrays
Resources:
Https://leetcode.com/discuss/103787/table-solution-pointers-solution-with-time-space-complexity
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Intersection of two Arrays II two arrays intersect the second