[leetcode350]Intersection of Two Arrays II求数组交集

时间:2023-03-09 23:06:20
[leetcode350]Intersection of Two Arrays II求数组交集
List<Integer> res = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i1 = 0;
int i2 = 0;
while (i1<nums1.length&&i2<nums2.length)
{
if (nums1[i1]<nums2[i2])
i1++;
else if (nums1[i1]>nums2[i2])
i2++;
else
{
res.add(nums1[i1]);
i1++;
i2++;
}
}
int[] num = new int[res.size()];
for (int i = 0; i < num.length; i++) {
num[i] = res.get(i);
}
return num;

受上一题的影响,本来想用hashset解决,但是发现不行,就换了排序然后遍历的方法,如果不相等,小的数的下边++,相等就添加