返回两个数组相交的数字
利用set集合解决 代码如下
现将一个数组写入set1,对于第二个数组,若其中的数字出现在1中,就将其写入2.最后将2中的数字写入a【】,返回即可
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for (int i = 0; i < nums1.length; i++) {
set1.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if(set1.contains(nums2[i])){
set2.add(nums2[i]);
}
}
int[] a = new int[set2.size()];
int i =0;
for (Integer l:set2) {
a[i++] = l;
}
return a;
}
}