Python Solution with 2 pointers O(n)


  • 1
    X
    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if len(nums) <= 1:
                return len(nums)
            else:
                head, tail = 1, 0
                while head < len(nums):
                    if nums[head] == nums[tail]:
                        head += 1
                    elif head - tail == 1:
                        tail, head = tail + 1, head + 1
                    else:
                        nums[tail + 1] = nums[head]
                        tail, head = tail + 1, head + 1
            return tail + 1
    

  • 0
    W

    You did not actually remove the duplicated elements. You just returned the number of non-repeated elements.


  • 0
    X

    @Weichuan3 Yes and that's specified in the question.


  • 0
    W

    @x-tron I see. You are right.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.