80. 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.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        l = 0
        r = 0
        n = len(nums)
        while r < n:
            #由于是保留 k 个相同数字,对于前 k 个数字,我们可以直接保留
            #对于后面的任意数字,能够保留的前提是:与当前写入的位置前面的第 k 个元素进行比较,不相同则保留
            if l < 2 or nums[l-2] != nums[r]:
                nums[l] = nums[r]
                l+=1
            r+=1
        return l

 

 

 

posted @ 2018-05-07 17:18  乐乐章  阅读(181)  评论(0编辑  收藏  举报