Intersection of two Arrays II two arrays of intersection II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.