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 set1 = new HashSet<>(); for (int n : nums1) set1.add(n); // 用第二个集合保存交集,天然保证唯一 HashSet 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 → int[] return arr; } }