编程语言
首页 > 编程语言> > 力扣-349题(Java)-双指针

力扣-349题(Java)-双指针

作者:互联网

题目链接: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的数组

    }
}

标签:Java,int,pos,nums1,力扣,array,pos2,349,pos1
来源: https://blog.csdn.net/qq_40467670/article/details/116333429