Leetcode 350. Intersection of Arrays II Java language

Source: Internet
Author: User

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 in the result should appear as many times as it shows in both arrays. The result can be on any order.

Test instructions: The intersection of two arrays, each element can appear multiple times, the returned array order is arbitrary.

Public class solution {    public int[] intersect (int[]  NUMS1,&NBSP;INT[]&NBSP;NUMS2)  {        List<Integer>  List=new arraylist<integer> ();         int length1= nums1.length;        int length2=nums2.length;         int[] ret=new int[math.min (length1,length2)];         int index=0;        hashmap<integer, Integer> map=new hashmap<integer,integer> ();         for (int i=0;i<length1;i++) {             if (!map.containskey (nums1[i)) {                 map.put (nums1[i],1);            }else{                 map.put (Nums1[i],map.get (nums1[i ]) +1);            }         }        for (int i=0;i<length2;i++) {             if (Map.containskey (nums2[i))  &&  map.get (Nums2[i])!=0) {                 map.put (Nums2[i],map.get (Nums2[i])-1);                 ret[index++]=nums2[i];             }        }         returN arrays.copyofrange (Ret,0,index);             }}

Ps:

1, first apply for a length is a smaller array of length arrays.

2. Use HashMap to store the number of occurrences of the first array.

3, traverse the second array, go to hashmap find, if it appears, then hashmap corresponding number minus 1, while adding the key to the array.

4, the final take part return ...

Leetcode 350. Intersection of Arrays II Java language

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.