- Set接口实例存储的是无序的、不重复的数据。List接口实例存储的是有序的、可以重复的元素。
- Set的实现类有HashSet,TreeSet
- List和数组类似,可以动态增长,根据实际存储的数据的长度自动增长List的长度。
题目:给定两个数组 nums1
和 nums2
,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
-
解题思路:
题目中要求每个元素都是唯一的,不同不考虑输出结果的顺序,这样就对应一种集合类型-> Set类型
使用set类型存储数组nums1,set中的元素不能重复,因此可以自动覆盖掉重复的数组。
然后遍历另外一个数组nums2,在set中查找nums2中的元素,只要存在,便将该元素防止在结果Set中。 最后将结果set转换成数组即可。 可以遍历set,将元素挪进数组即可。 -
代码
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 1){
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
HashSet<Integer> resSet = new HashSet<>();
// 遍历数组1
for (int i : nums1) {
set1.add(i);
}
// 遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)){
resSet.add(i);
}
}
int[] arr = new int[resSet.size()];
int j = 0;
for (int i : resSet) {
arr[j++] = i;
}
return arr;
}
}