0
点赞
收藏
分享

微信扫一扫

080.remove-duplicates-from-sorted-array-ii

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 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 2:
            return len(nums)
        cnt = 0
        j = 1
        for i in xrange(1, len(nums)):
            if nums[i] == nums[i - 1]:
                cnt += 1
                if cnt < 2:
                    nums[j] = nums[i]
                    j += 1
            else:
                nums[j] = nums[i]
                j += 1
                cnt = 0
        return j
举报

相关推荐

0 条评论