利用哈希表set方法来做
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int [] arr = new int [0];
//如果两个数组有一个为零的话便直接返回空数组
if (nums1.length == 0 || nums2.length == 0 ) {
return arr;
}
//定义两个Set变量 set01是为了存储第一个数组 而reset是来存储交集
Set<Integer> set01 = new HashSet<>();
Set<Integer> reset = new HashSet<>();
//遍历第一个数组把第一个数组
for (int i = 0;i<nums1.length ;i++ ) {
set01.add(nums1[i]);
}
//定义两个数组长度
int a = nums1.length;
int b = nums2.length;
//判断哪一个数组长然后从短数组中挑交集
if (a>b) {
//用两个for循环开启遍历
for (int i = 0;i<nums2.length ;i++ ) {
for (int j = 0;j<nums1.length ;j++ ) {
if (nums1[j] == nums2[i]) {
//添加元素
reset.add(nums2[i]);
}
}
}
}else{
for (int i = 0;i<nums1.length ;i++ ) {
for (int j = 0;j<nums2.length ;j++ ) {
if (nums1[i] == nums2[j]) {
reset.add(nums1[i]);
}
}
}
}
//定义一个新数组长度与reset一样
int[] arr1 = new int[reset.size()];
//下标标记
int j = 0;
//把reset转为数组
for (int i : reset) {
arr1[j++] = i;
}
return arr1;
}
}