LeetCode - 350. Intersection of Two Arrays II
链接
350. Intersection of Two Arrays II
题意
给定两个数组,找出交集(注意交集中元素的次数应该和两个数组中出现的次数一致、顺序可任意)
思路
将两个数组排序,各设置一个指针依次遍历两个数组,若两个数组当前遍历值相等,则add到一个list中(保存答案)。
若不同,则分情况:
- 数组1值小于数组2值,则向后移动数组1的指针
- 数组1值大于数组2值,则向后移动数组2的指针
(这是为了找到相等的元素)
直到有一个数组遍历完成,最后将list转为数组
代码
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> list=new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i=0,j=0;
while(i<nums1.length&&j<nums2.length){
if(nums1[i]==nums2[j]){
list.add(nums1[i]);
i++;
j++;
}else if(nums1[i]<nums2[j]){
i++;
}else{
j++;
}
}
int[] res=new int[list.size()];
for(int k=0;k<res.length;k++){
res[k]=list.get(k);
}
return res;
}
}