题目链接:https://leetcode-cn.com/problems/intersection-of-two-arrays/
题目如下:
class Solution { public int[] intersection(int[] nums1, int[] nums2) { int len1=nums1.length,len2=nums2.length; //排序确保都是升序 Arrays.sort(nums1); Arrays.sort(nums2); int pos1=0,pos2=0; int[] array=new int[len1>len2?len2:len1]; int pos=0; while(pos1<len1&&pos2<len2){//只要有一个到头,那就over,不存在重复元素 if(nums1[pos1]==nums2[pos2]){ array[pos++]=nums1[pos1++];//遇到相同元素,就放入array if(pos>1&&array[pos-1]==array[pos-2]) pos--;//判别是否重复 pos2++; }else if(nums1[pos1]<nums2[pos2]) pos1++; else if(nums1[pos1]>nums2[pos2]) pos2++; } return Arrays.copyOfRange(array,0,pos);//得出位置从0到pos的数组 } }