Given two arrays, write a function to compute their intersection.
Example
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
利用较小的数组建m(下面代码并没有这个优化)注意当m为空时跳出循环 在nums2较大的情况下避免过多无用计算
1 public class Solution { 2 /** 3 * @param nums1 an integer array 4 * @param nums2 an integer array 5 * @return an integer array 6 */ 7 public int[] intersection(int[] nums1, int[] nums2) { 8 // Write your code here 9 if(nums1==null||nums2==null) return null; 10 11 if(nums1.length==0||nums2.length==0) return new int[0]; 12 13 Map<Integer, Integer> m = new HashMap<Integer, Integer>(); 14 Map<Integer, Integer> resM = new HashMap<Integer, Integer>(); 15 16 for(int i : nums1){ 17 if(m.containsKey(i)){ 18 m.put(i, m.get(i)+1); 19 }else{ 20 m.put(i, 1); 21 } 22 } 23 for(int i:nums2){ 24 if(m.containsKey(i)){ 25 if(m.get(i)==1){ 26 m.remove(i); 27 }else{ 28 m.put(i, m.get(i)-1); 29 } 30 if(resM.containsKey(i)){ 31 resM.put(i, resM.get(i)+1); 32 }else{ 33 resM.put(i, 1); 34 } 35 if(m.size()==0) break; 36 } 37 } 38 List<Integer> res = new ArrayList(); 39 for(Map.Entry<Integer, Integer> entry: resM.entrySet()){ 40 int vCnt = entry.getValue(); 41 int key = entry.getKey(); 42 while(vCnt>0){ 43 res.add(key); 44 vCnt--; 45 } 46 } 47 int[] resInt = new int[res.size()]; 48 int index =0; 49 for(Integer i : res){ 50 resInt[index++] = i; 51 } 52 return resInt; 53 } 54 }