LeetCode80:Remove Duplicates from Sorted Array II

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 nums being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.

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 nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

LeetCode:链接

第一种方法:使用两个指针prev和curr,判断A[curr]是否和A[prev]、A[prev-1]相等,如果相等curr指针继续向后遍历,直到不相等时,将curr指针指向的值赋值给A[prev+1],这样多余的数就都被交换到后面去了。最后prev+1值就是数组的长度。

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 2:
            return len(nums)
        pre = 1
        cur = 2
        while cur < len(nums):
            if nums[cur] == nums[pre] and nums[pre] == nums[pre-1]:
                cur += 1
            else:
                pre += 1
                nums[pre] = nums[cur]
                cur += 1
        return pre + 1

第二种方法:在每一次插入过程中,其实只要把要插入的元素和倒数第二个元素进行比较,如果相同,就忽略,因为倒数第一个数是夹在它们中间的,如果它们相等,那么就会有三个数相等;如果不同,就可以插入,因为在这样的情况下,最多只有倒数第二、倒数第一两个数相等。

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        for i in range(len(nums)):
            if count < 2 or nums[count - 2] != nums[i]:
                nums[count] = nums[i]
                count += 1
        return count

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值