leetcode–两个数组交集2
题目描述
思路分享
两个数组的交集2与两个数组的交集1的区别在于交集1不准重复但是交集2可以重复,
1、我们选定数组长度较短的一个进行hashmap赋值,如何选择长度较短的一个本题目中用了递归算法保证nums1一直都是最短的。其中k为数值,v为数值出现的次数。
2、在nums1用hashmap赋值以后我们还需要对nums2进行遍历,在nums2遍历的过程中我们需要通过nums1的hashmap的value值进行判断nums1中有没有出现这个数值。
3、如果hashmap存在那么将数值存储进入数组中,并将相应的hashmap的value值进行减一。
代码
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length){
return intersect(nums2,nums1);
}
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i : nums1) {
if (hashMap.containsKey(i)){
hashMap.put(i,hashMap.get(i)+1);
}else {
hashMap.put(i,1);
}
}
int[] res = new int[nums1.length];
int index = 0;
for (int i : nums2) {
Integer count = hashMap.getOrDefault(i, 0);
if (count >= 1){
res[index++] = i;
count--;
if (count > 0){
hashMap.put(i,count);
}else {
hashMap.remove(i);
}
}
}
return Arrays.copyOfRange(res,0,index);
}
}
参考
https://leetcode.cn/problems/intersection-of-two-arrays-ii/