LeetCode80. Remove Duplicates from Sorted Array II(思路及python解法)

本文介绍了一种在不使用额外空间的情况下,修改输入数组以确保每个元素最多只出现两次的算法。通过记录当前元素的出现次数,当次数超过两次时,从数组中移除该元素,同时更新数组长度和计数器。此方法适用于已排序的数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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 1:

Given nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of numsbeing 1, 1, 2, 2
and 3 respectively.


Example 2:
Given nums = [0,0,1,1,1,1,2,3,3], Your function should return length = 7, with the first seven elements of numsbeing modified to 0, 0, 1, 1, 2, 3 and 3 respectively.


列表已经从小到大排序完了,删除数字重复出现次数大于2次的,需要原地操作。

所以只需要记录当前数字出现次数即可。dup表示当前数字出现的次数。

如果dup>2则删除当前数字,注意此时nums的长度,记录位置的n,重复次数dup都需要-1。

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length=len(nums)
        n=1
        dup=1
        while n<length:
            if nums[n]==nums[n-1]:
                dup+=1
                if dup>2:
                    nums.remove(nums[n])
                    dup-=1
                    length-=1
                    n-=1
            else:
                dup=1
            n+=1      

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值