本题跟之前有所变化,要求找出两个数组中所有重复数字,包括重复的。我们用map记录值与次数,当次数小于1时,不记录,其余记录,代码如下:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map = new HashMap<Integer, Integer>();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < nums1.length; 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 < nums2.length; i++) {
if(map.containsKey(nums2[i])&&map.get(nums2[i])>0){
map.put(nums2[i], map.get(nums2[i])-1);
list.add(nums2[i]);
}
else
continue;
}
int[] a = new int[list.size()];
int i =0;
for (Integer l:list) {
a[i++] = l;
}
return a;
}
}