思路
1,将两个数组分别排序
2,同时遍历两个数组,将相同的数字放入set 集合
3,将set 集合转换为 数组
代码
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
LinkedHashSet<Integer> res_set = new LinkedHashSet<Integer>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int p1=0;
int p2=0;
int size1 = nums1.length;
int size2 = nums2.length;
while (p1<size1 && p2<size2) {
if (nums1[p1]==nums2[p2]){
res_set.add(nums1[p1]);
p1++;
p2++;
} else if (nums1[p1]>nums2[p2]){
p2++;
} else {
p1++;
}
}
int[] res = new int[res_set.size()];
Iterator<Integer> it =res_set.iterator();
int i=0;
while (it.hasNext()){
res[i]=it.next();
i++;
}
return res;
}
}