原题链接:349. 两个数组的交集 - 力扣(LeetCode): https://leetcode.cn/problems/intersection-of-two-arrays/
给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000示例1
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例2
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的
// https://github.com/cc01cc/algorithm-learning/blob/master/practice/leetcode/LeetCode349_01_01.java
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
public class LeetCode349_01_01 {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
for (int i : nums1) {
set1.add(i);
}
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
return resSet.stream().mapToInt(x -> x).toArray();
}
@Test
public void test() {
int[] nums1 = new int[]{1, 2, 2, 1};
int[] nums2 = new int[]{2, 2};
int[] res = new LeetCode349_01_01().intersection(nums1, nums2);
for (int i : res) {
System.out.print(i + "\t");
}
}
}