思路
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;
}
}

博客介绍了求两个数组相同元素的思路。先分别对两个数组排序,接着同时遍历这两个数组,把相同数字放入 set 集合,最后将 set 集合转换为数组,并给出了代码。
665

被折叠的 条评论
为什么被折叠?



