350 Intersection of Two Arrays II

Given two arrays, write a method to compute their intersection.
For example:
given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
       The number of occurrences of each element in the output result should be the same as the number of elements in the two arrays The number of occurrences is the same.
       We can ignore the order of output results.
Follow up:
    what if the given array is already sorted? How would you optimize your algorithm?
    If the size of nums1 is much smaller than nums2, which method is better?
    If the elements of nums2 are stored on disk and memory is limited, you can't 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324382852&siteId=291194637