Algorithm/src/main/java/hash/Intersection.java
2025-05-29 15:34:47 +08:00

34 lines
1.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}