难度:简单
给定两个数组 nums1 和 nums2 ,返回它们的交集 。输出结果中的每个元素一定是唯一 的。我们可以不考虑输出结果的顺序 。
题目链接
Set的使用
数组
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return null;
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
//遍历数组1
for (int sum : nums1) {
set1.add(sum);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int sum : nums2) {
if (set1.contains(sum)) {
set2.add(sum);
}
}
int[] result = new int[set2.size()];
int start = 0;
//将结果几何转为数组
for (int sum : set2) {
result[start] = sum;
start++;
}
return result;
}
}
list集合
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
throw new IllegalArgumentException("nums1 or nums2 not empty");
}
// 1、创建set集合,set集合的作用是去重
Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
// 2、遍历另外一个数组,找出相同的元素,并放入list集合中
List<Integer> list = new ArrayList<>();
Arrays.stream(nums2).forEach(item -> {
if (set.contains(item)) {
list.add(item);
set.remove(item);
}
});
// 3、返回结果
return list.stream().mapToInt(Integer::valueOf).toArray();
}
}