Remove Duplicates from Sorted Array II

Question

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.

Tags

  • Array
  • Two Pointers

Thought

Similar to the previous problem, but we need to add the consideration for the duplicated elements.

Code

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

results matching ""

    No results matching ""