O(1)删除排序数组中的冗余元素,允许多冗余1个

本文介绍了一种解决LeetCode上Remove Duplicates from Sorted Array II问题的方法,该方法使用有限状态自动机处理数组,确保每个元素最多出现两次,并保持O(1)的空间复杂度。
  1. Remove Duplicates from Sorted Array II
    https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

删除元素,空间复杂度要求O(1)。
用了一个有限状态自动机的方法。状态机的状态为”当前元素重复的数目“,输入为”遍历到的元素相比新数组最后一个位置改变还是不改变“

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)
        i = 0
        cnt = 1
        j = 1
        while j < length:
            n = nums[j]
            if cnt == 1:
                if n == nums[i]:
                    i += 1
                    nums[i] = n
                    cnt += 1
                else:
                    i += 1
                    nums[i] = n
                    cnt = 1                    
            elif cnt == 2:
                if n == nums[i]:
                    pass
                else:
                    i += 1
                    nums[i] = n
                    cnt = 1    
            j += 1
        return i+1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值