Intersection of two Arrays II (intersection of two arrays)

Source: Internet
Author: User
Topic

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:

Each of the element in the result should appear as many times as it shows in both arrays.
The result can be as any order.
the

The intersection of two arrays, which contains the maximum number of occurrences of each number in the intersection as much as possible. Solving

Ideas and 349 ideas the same http://blog.csdn.net/xunalove/article/details/79372497, but not to heavy, while Nums1[i] in Nums2, delete nums2 in a nums1[i] Elements. The Python code is implemented. However, in C + + vector, remove () is the deletion of all equal to Nums1[i in nums2, not desirable.
Therefore, another method is used to save the number of occurrences of each number in the NUMS1 by using the map, traversing nums2 and processing. C + + code

Class Solution {public
:
    vector<int> intersect (vector<int>& nums1, vector<int>& NUMS2) {

        vector<int>res;
        map<int,int>m;

        for (int i=0; i<nums1.size (); i++)
        {
            m[nums1[i]]++;
        }
        for (int i=0; i<nums2.size (); i++)
        {
            if (m[nums2[i]]>0)
            {
                res.push_back (nums2[i));
                m[nums2[i]]--
            }
        }
        return res;
    }
;
Python code
Class Solution (object):
    def intersect (self, NUMS1, NUMS2): ""
        : Type Nums1:list[int]
        : type NUMS2: List[int]
        : rtype:list[int]
        ""
        res = []
        for I in range (0, Len (nums1)):
            if Nums1[i] in NUMS2:
                Res.append (Nums1[i])
                nums2.remove (Nums1[i]) #删除nums2中该数
            If Len (nums2) ==0 or Len (nums1) ==0:
                return Res return

        Res

Python code is simpler

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.