26. Remove Duplicates from Sorted Array

    xiaoxiao2021-03-25  82

    Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

    Do not allocate extra space for another array, you must do this in place with constant memory.

    For example, Given input array nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

    问题:不允许开辟额外空间,重复元素的话保留首次出现的

    解决:在len的后一位i开始遇到重复,则i开始后移直到非重复的出现,将新元素放到len后面

    public int removeDuplicates(int[] nums) { if(nums.length==0||nums==null) return 0; int len=0; for(int i=1;i<nums.length;i++){ if(nums[i]!=nums[len]){ nums[++len]=nums[i]; continue; } } for(int i=0;i<=len;i++){ System.out.print(nums[i]+"\t"); } return len+1; }

    转载请注明原文地址: https://ju.6miu.com/read-16040.html

    最新回复(0)