Algorithm/src/main/java/hash/Intersection.java

34 lines
1.0 KiB
Java
Raw Normal View History

2025-05-29 15:34:47 +08:00
package hash;
import java.util.HashSet;
/**
* 题目 349. 两个数组的交集 ( Intersection)
* 描述给定两个数组 nums1 nums2 返回 它们的 交集 输出结果中的每个元素一定是 唯一 我们可以 不考虑输出结果的顺序
*
示例 1
输入nums1 = [1,2,2,1], nums2 = [2,2]
输出[2]
* 链接https://leetcode.cn/problems/intersection-of-two-arrays/
*/
public class Intersection {
public int[] intersection(int[] nums1, int[] nums2) {
// 把 nums1 转成集合
HashSet<Integer> set1 = new HashSet<>();
for (int n : nums1) set1.add(n);
// 用第二个集合保存交集,天然保证唯一
HashSet<Integer> resSet = new HashSet<>();
for (int n : nums2) {
if (set1.contains(n)) resSet.add(n);
}
int[] arr = new int[resSet.size()];
int j = 0;
for(int i : resSet){
arr[j++] = i;
}
// Set<Integer> → int[]
return arr;
}
}