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循环,不停和当前放置的数比较~~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值