给定一个已排序的数字数组,原地移除重复元素使每个元素只出现一次并返回新数组的长度。

不要分配额外的空间给其它数组,你必须通过原地修改输入的数组解决这个问题,且空间复杂度为O(1)。

Example 1:

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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

说明:

为返回值是整型数字但你的答案却是数组感到疑惑?

注意输入的数组是通过引用传递进去函数的,这意味着对输入数组的修改也会被调用者知道。

你可以认为内部是这样实现的:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

解法1:

双指针解法:

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    if (!nums.length) return 0;
    let last = 0; //上一个数的下标
    for (let curr = 1; curr < nums.length; curr++) {
        //如果和上一个数值一样,继续往下
        if (nums[curr] == nums[last]) continue;
        //如果不一样,赋值到下一个元素位
        nums[++last] = nums[curr];
    }
    return last + 1;
};