給定兩個數組,編寫一個函數來計算它們的交集。
將長度小的數組放入hashmap,記錄出現的次數,遍歷另一個數組,找出交集
class Solution {public int[] intersect(int[] nums1, int[] nums2) {ArrayList<Integer> res=new ArrayList<>();Map<Integer,Integer> map=new HashMap<>();int[] tagert= nums1.length>nums2.length?nums2:nums1;int[] tagert2= nums1.length>nums2.length?nums1:nums2;for(int c:tagert) map.put(c,map.getOrDefault(c,0)+1);for(int c:tagert2)if(map.containsKey(c)&&map.get(c)>0){res.add(c);map.put(c,map.get(c)-1);}int[] res2=new int[res.size()];for(int i=0;i<res.size();i++)res2[i]=res.get(i);return res2;
}
}