两个数组的交集II
题目描述:
给定两个数组nums1,nums2,编写一个函数来计算它们的交集。1
- 分析:
- 采用哈希表记录一个数组 nums1 中各个元素出现的次数
- 再次遍历数组 nums2,将共元素保存进数组中,更新哈希表
- 代码部分:
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1.length <= 0 || nums2.length <= 0) return new int[]{};
HashMap<Integer,Integer> map = new HashMap<>();//(元素,元素个数))
int[] res = new int[Math.min(nums1.length,nums2.length)];
int idx = 0;
for(int i : nums1){
map.put(i,map.getOrDefault(i,0) + 1);
}
for(int j : nums2){
if(map.getOrDefault(j,0) >= 1){
res[idx++] = j;
map.put(j,map.get(j) - 1);
}
}
return Arrays.copyOfRange(res, 0, idx);
}
https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/ ↩︎