Leetcode 349.两个数组的交集(Intersection of two arrays)
题目链接🔗
给定两个数组 nums1和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
示例 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] 也是可通过的
提示:
- 1 <= nums1.length, nums2.length <= 1000
- 0 <= nums1[i], nums2[i] <= 1000
思路
直接使用Set将nums1的内容添加,将nums2的内容进行比对,若存在相同的值则将该值存入新的Set(为什么不直接存在数组中是因为不知道还有多少个值所以无法定义长度),最后将Set转为数组即可。
代码实现
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> res = new HashSet<>();
for(int num : nums1) {
set.add(num);
}
for(int num : nums2) {
if(set.contains(num)) {
res.add(num);
}
}
// 方法1: 使用stream流将Set转为数组
return res.stream().mapToInt(Integer::intValue).toArray();
// 方法2: 使用for循环创建一个数组并存入Set中的值
int[] arr = new int[res.size()];
int j = 0;
for(int i : res) {
arr[j++] = i;
}
return arr;