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