LeetCode 26 Remove Duplicates from Sorted Array 删除有序数组中的重复元素

题目描述

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

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:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,,,,,_]

题解

/**
 * 维护两个指针p=0,q=1, q递增,如果p,q值相等,说明重复,q++, 否则说明不重复,将q的值覆盖到++p的位置
 * @param {number[]} nums
 * @return {number}
 */
const removeDuplicates = (arr) => {
    let p = 0, q = 1
    while (q < arr.length) {
        if (arr[p] === arr[q]) {
            q++
        } else {
            arr[++p] = arr[q]
        }
    }
    return p + 1
}

/**
 * 
 * 快指针用于遍历数组,慢指针用于指向待删除/替换的元素, 即慢指针表示下一个不同元素要填入的下标位置
 * 数组长度大于0时,数组最少包含一个元素,删除重复元素之后数组中也至少有一个元素,因此慢指针可以从1开始,每需要替换一个就+1
 * 最后数组长度就等于基本长度1+替换次数长度 = slow
 * @param {*} nums 
 * @returns 
 */
var removeDuplicates1 = function (nums) {
    const n = nums.length;
    if (n === 0) {
        return 0;
    }
    let fast = 1, slow = 1;
    while (fast < n) {
        if (nums[fast] === nums[fast - 1]) {
            fast++
            continue
        }
        nums[slow] = nums[fast]
        slow++
        fast++
    }
    return nums.length = slow
};

var removeDuplicates2 = function (nums) {
    const len = nums.length
    if (len = 1) return len
    let fast = 1, slow = 1
    while(fast < len){
        if(nums[fast] !== nums[fast - 1]){
            nums[slow] = nums[fast]
            slow ++ 
        }
        fast ++ 
    }
    return nums.length = slow 
};
posted @ 2022-07-18 16:25  IslandZzzz  阅读(15)  评论(0编辑  收藏  举报