题目
https://leetcode-cn.com/problems/intersection-of-two-arrays/
思路
在有思路之前,要知道HashSet的一些性质:
- 底层数据结构是哈希表
- 存储元素的顺序和遍历获取出来的顺序可能不一致
- 没有索引
- 集合中不能存储重复元素
代码验证
知道性质后,思路就变得简单
- 先把第一个数组加进set,然后里面就是不重复的数字。
- 在加第二个数组放进set的时候,用contains方法判断是否有一样的元素,再放进set。
- 用result数组装下第二个set然后返回result
代码实现
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<>();
HashSet<Integer> set2 = new HashSet<>();
for(int i : nums1){
set1.add(i);
}
for(int i : nums2){
if(set1.contains(i)){
set2.add(i);
}
}
int[] result = new int[set2.size()];
int index = 0;
for (int i : set2) {
result[index++] = i;
}
return result;
}
}