public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int[]temp;
if(nums1.length<nums2.length)
{
temp=nums2;
nums2=nums1;
nums1=temp;
}
int i=0;
int j=0;
ArrayList<Integer> result=new ArrayList<>();
while(i<nums1.length&&j<nums2.length)
{
if(nums1[i]==nums2[j])
{
result.add(nums1[i]);
i++;
j++;
}
else if(nums1[i]<nums2[j])
{
i++;
}
else
{
j++;
}
}
Object[] tempArray= result.toArray();
int[] toreturn=new int[tempArray.length];
for(int k=0;k<tempArray.length;k++)
{
toreturn[k]=(Integer)tempArray[k];
}
return toreturn;
}
}
leetcode Intersection of Two Arrays II
最新推荐文章于 2021-09-18 14:50:01 发布
本文介绍了一种求两个整数数组交集的算法实现。通过排序和双指针技巧,该方法有效地找到并返回两个输入数组共有的元素。文章详细展示了Java代码实现过程,包括数组操作、结果收集及转换。
907

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



