26. Remove Duplicates from Sorted Array

来源:互联网 发布:block matching算法 编辑:程序博客网 时间:2024/04/30 14:38

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;    }


0 0