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 by modifying the input array in-place with O(1) extra memory.

翻译

给定一个有序数组,移除其中的重复元素,形成新的数组,返回新数组的长度。注意不能占用额外的内存。

题目中有点没说清楚,其实数组没有变,只是前几位换成了互不重复的数字,后面的还是原来数组里的数字。以下面的Example为例,其实经过程序调整,新的数组为[1,2,2],只是你返回的长度为2,所以只看前两位,就是[1,2],其实第三位还是原来数组里的第三位。

Example:

Given 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.


我的答案

class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length==0)
return 0;//数组长度为0的情况
int temp=0;
for (int i=1;i<nums.length;i++){//下标为0的数肯定不会和之前重复(因为是第一个)
while(nums[i]==nums[i-1]&&(i<nums.length-1)){//检测是否和之前重复,是的话继续往后看,i=i+1;不重复,或者到了最后一个元素,则跳出循环
i=i+1;
}
if(nums[i]!=nums[i-1]){//因为我们不知道之前跳出循环是因为发现第i个和第i-1个元素不重复了还是到了数组末尾,所以需要判断第i个元素是否等于第i-1个元素
temp++;
nums[temp]=nums[i];
}

}
temp=temp+1;//temp从0开始,所以需要加1为新数组长度
return temp;

}
}

大神答案(抱歉我不知道怎么看作者姓名,是discuss区域里的)

public int removeDuplicates(int[] A) {
    if (A.length==0) return 0;//注意考虑特殊情况,长度为0
    int j=0;//把j作为一个指针
    for (int i=0; i<A.length; i++)
        if (A[i]!=A[j]) A[++j]=A[i];//指下一个数,和当前数相同则继续往下,不同则赋值,且j向下指。
    return ++j;
}
比我高明的地方在于省略了while循环,不停和当前放置的数比较~~
原文地址:https://www.cnblogs.com/mafang/p/8306119.html