两个数组的交集
解题思路:没有个数限制,不重复,可以无序----->Set集合
Set集合常用的实现方法为HashSet。将第一个数组的元素存储到ASet集合中,此时Set集合只有第一个数组中所有不重复的元素,再将第二个数组中,且在Aset集合中的(使用contains()方法)存储到第二个集合Bset中,增强for循环将Bset放到数组中,返回数组即可。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet <Integer> aset= new HashSet<>();
HashSet<Integer> bset= new HashSet<>();
for(int i : nums1){
aset.add(i);
}
for(int j:nums2){
if(aset.contains(j)){
bset.add(j);
}
}
int [] a =new int[bset.size()];
int c = 0;
for(int k:bset){
a[c++] = k;
}
return a;
}
}