给定两个数组,编写一个函数来计算它们的交集。
将长度小的数组放入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;
}
}