[leedcode 26] Remove Duplicates from Sorted Array

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.

public class Solution {
    //本题有个要求:需要原地进行处理,即不能占用额外空间。因此考虑声明一个指针,指针前面的值都是非重复的
    //然后遍历一遍数组,每个值与其前一个值进行比较,若相同,则前进索引,若不同,则将此值放入数组前面
    //以下是一种解法,次解法的缺点是,当出现不重复的数组时,nums[start++]=nums[index++]扔会运行
    //本题需要注意,start的初始值
    
    public int removeDuplicates(int[] nums) {
       if(nums.length==0) return 0;
        int start=1;
       int index=1;
        while(index<nums.length){
           if(nums[index]==nums[index-1]){
               index++;
           }else{
               nums[start++]=nums[index++];
               
           }
       }
       return start;
            
    }
    
}

 

你可能感兴趣的:(remove)