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


    题目描述

    Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. 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,1,2,2,3]
    Output: 5, nums = [1,1,2,2,3,_]
    Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 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,1,2,3,3]
    Output: 7, nums = [0,0,1,1,2,3,3,,]
    Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
    It does not matter what you leave beyond the returned k (hence they are underscores).

    题解

    /**
     * 快慢指针
     * 快指针从索引2开始遍历整个数组,
     * 慢指针从索引2开始,慢指针指向下一个被不同元素覆盖的元素,因为删除/替换之后至少有两个元素
     * 因为是有序数组,nums任意三个元素,只要两头相等,那么中间那个元素必然相等, 即这区间内三个元素全部相等
     * 即,对于nums[slow - 2] = nums[fast], 必然有 nums[slow-2] = nums[slow - 1] = nums[fast]
     * 因此判断需要覆盖的case就是: nums[slow - 2] !== nums[fast]
     * @param {number[]} nums
     * @return {number}
     */
    var removeDuplicates = function (nums) {
        const len = nums.length
        if (len <= 2) return len
        let slow = 2, fast = 2
        while (fast < len) {
            if (nums[slow - 2] !== nums[fast]) {
                nums[slow ++] = nums[fast]
            }
            fast++
        }
        return nums.length = slow  
    }
    
  • 相关阅读:
    JS/JQuery下拉列表选中项的索引
    数据挖掘
    Sencha安装
    新的开始
    jquery multi scrollable 同步的问题
    dom4j
    rest
    spring 2
    spring framework3.0开发
    笔记Spring in action
  • 原文地址:https://www.cnblogs.com/ltfxy/p/16492608.html
Copyright © 2020-2023  润新知