Easy understanding Python solution with Time O(n) Space O(1)


  • 0
    G
    class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if (len(nums)==0):
            return 0
        elif (len(nums)==1):
            return 1
        p = 1
        prev = (nums[0])
        for i in range(1,len(nums)):
            if (nums[i]==prev):
                continue
            nums[p]=nums[i]
            p+=1
            prev=nums[i]
        return p

  • 2
    Z

    You can remove most checkings

    def removeDuplicates(self, nums):
        l,r = 0,0
        for r in range(1,len(nums)):
            if nums[l] != nums[r]:
                l +=1
                nums[l] = nums[r]
        return l+1 if nums else 0

  • 0
    G

    that's much more concise!


Log in to reply
 

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