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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章