Given two arrays, write a method to calculate their intersection.
For example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Attention:
The number of occurrences of each element in the output should coincide with the number of occurrences of the element in two arrays.
We can not consider the order of the output results.
Follow:
What if the given array is already sorted? How will you optimize your algorithm?
If the size of the NUMS1 is much smaller than the NUMS2, which method is better?
If the NUMS2 element is stored on disk, the memory is limited, you cannot load all the elements into memory at once, what should you do?
See: https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
C++:
Class Solution {public: vector<int> intersect (vector<int>& nums1, vector<int>& nums2) { unordered_map<int,int> m; vector<int> Res; for (int num:nums1) { ++m[num]; } for (int num:nums2) { if (m[num]-->0) { res.push_back (num); } } return res; }};
Reference: https://www.cnblogs.com/grandyang/p/5533305.html
Intersection of two Arrays II two arrays of intersection II