ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-07-19 11:33:07  阅读:145  来源: 互联网

标签:elements nums Duplicates 元素 Remove II slow array first


题目描述

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  
}

标签:elements,nums,Duplicates,元素,Remove,II,slow,array,first
来源: https://www.cnblogs.com/ltfxy/p/16492608.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有