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


一开始也想到了双指针 first指向重复的第一个元素 second从first开始找第一个不重复元素 这样出现了两个问题
1.我是不是需要把first后面的重复元素都替换掉 
比如 1,2,2,2,2,3,4
如果只覆盖掉第一个重复元素 变为
1,2,3,2,2,4
那么怎么判断后面的2是重复元素呢 还需要set维护
2.如果需要覆盖掉后面所有重复元素 那么对于每一个重复元素 都需要在其后面遍历寻找到非重复元素 感觉时间复杂度O(n^2) 

像下面这样
    public int removeDuplicates(int[] nums) {
        int index = 0, count = 0;
        while (index < nums.length) {
            int pre = nums[index];
            if (++index == nums.length) return ++count;
            
            if (nums[index] == pre) {
                int start = index;
                int end = start;
                while (end<nums.length && nums[end]==pre) {
                    end++;
                }
                if (end == nums.length) return ++count;
                
                for (int i=start; i<end; i++) {
                    nums[i] = nums[end];
                }
            }
            count++;
        }
        return count;
    }
实际上是不需要这样的 

1.不需要知道这个元素和前面的所有元素是否重复 只要和后面的不相等 替换就可以了  注意是sorted array
比如 1,2,2,2,2,3,4
如果只覆盖掉第一个重复元素 变为
1,2,3,2,2,4
start指向3后面的2 之后发现4和2不相等 用4覆盖掉2就可以了
2.实际上不是每个元素都需要向后遍历 只要end到达末尾 就结束了 所以时间复杂度O(n)

下面的solution更加简洁
public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值