两个数组的交集
📃 题目描述
🔔 解题思路
首先我们需要注意的是,两个数组的交集是不包含重复数字的,那最简单的,我们可以将两个数组的交集存在 Set 中,由 Set 来帮我们去重。
那这个题目其实我们需要两个 Set,整体思路如下:
- 先处理数组 nums1 将其存入一个 Set
- 遍历数组 nums2,若某个数字在 Set 中存在,则将其存入交集 Set 中
- 最后返回这个 Set 即可
另外,上一题我们说过,对于哈希表中的 key,如果哈希值比较连续且固定,我们可以用数组的下标来等同,那显然,对于这个题目,不适合用数组来代替哈希表。
代码演示
package com.kami.leetcode.hash_table;
import java.util.HashSet;
import java.util.Set;
/**
* @Description: TODO
* @author: scott
* @date: 2022年01月17日 9:10
*/
public class Solution_349 {
public int[] intersection(int[] nums1, int[] nums2){
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0){
return new int[0];
}
//存储交集
Set<Integer> resSet = new HashSet<>();
//存储num1
Set<Integer> setH = new HashSet<>();
//先存储num1
for (int i : nums1) {
setH.add(i);
}
//遍历num2,如果setH中包含了其中的值,存储到存储交集中
for (int i : nums2) {
if(setH.contains(i)){
resSet.add(i);
}
}
//resSet的值转为数组
int[] res = new int[resSet.size()];
int index = 0;
for (Integer integer : resSet) {
res[index++] = integer;
}
return res;
}
}