题目:力扣
思路:
题目中描述:输出结果中的每个元素一定是 唯一 的,说明我们结果一定唯一,是不重复的。我们就可以用set来存储,set存储的就是不重复的数据。
代码:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> numsSet = new HashSet<Integer>();
Set<Integer> resSet = new HashSet<Integer>();
for (int i : nums1) {
numsSet.add(i);
}
for (int i : nums2) {
if (numsSet.contains(i)) {
resSet.add(i);
}
}
return resSet.stream().mapToInt(x -> x).toArray();
}
}