Remove Duplicates from Sorted Array II

本文探讨了在有序数组中去除超过两次的重复元素问题,提出了两种算法解决方案。一种使用计数器方法,另一种利用排序特性简化操作,提高了效率。

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

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

Remove Duplicates from Sorted Array II是Remove Duplicates from Sorted Array的升级版本,即对于一个有序数组,允许最多有两个重复元素。

一个简单直接的思路是维护一个计数器count,用来记录同一个数值元素的出现次数。出现次数为3次即以上,该元素不放入结果的有序数组中。代码如下:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        end = 0
        length=len(nums)
        count = 1
        for i in xrange(1,length):
            temp = nums[i]
            if temp == nums[end] :
                count+=1
                if count>2:
                    continue
                end+=1
                nums[end]=temp
            else:
                count=1
                end+=1
                nums[end]=temp

        return end+1

以上代码中,end为当前结果数组的最后一位的index,也即是用来被比较的元素的index。当前元素和cur所代表的数不一样时,count重新置为1,否则加1.算法遍历了一遍数组,时间复杂度为O(n),数组inplace处理,额外空间为count,cur,temp等变量的空间,空间复杂度为O(1).

以上算法没有利用排序数字本身的特性,即连续区间首尾元素相等,则该区间所有元素相等,所以在最多只有两个重复元素时,我们可以直接比较nums[i]和nums[end-1],如果nums[i]=nums[end-1]则nums[i]=nums[end-1]=nums[end],省去了 count的计数操作,代码也大大简化:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length=len(nums)
        if length<3:
            return length
        end = 1
        for i in xrange(2,length):
            temp = nums[i]
            if temp != nums[end-1] :
                end+=1
                nums[end]=temp

        return end+1

时间复杂度O(n),空间复杂度O(1).

转载于:https://www.cnblogs.com/sherylwang/p/5384563.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值