题目
给定两个数组 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
代码
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> a = new HashSet<>();
Set<Integer> b = new HashSet<>();
for(int i:nums1)
{
a.add(i);
}
for(int i:nums2)
{
if(a.contains(i))
{
b.add(i);
}
}
int arr[]=new int[b.size()];
int j=0;
for(int i:b)
{
arr[j++]=i;
}
return arr;
}
}
题目中注意点
最后一步将Set集合转换为数组的时候,toArray方法返回的是一个Integer类型的数组,不是一个int型的数组,要用增强for重新赋值。