Simple Python solution


  • 0
    B
    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            nums[:] = [nums[x] for x in range(len(nums)) if nums[x] != nums[x-1] or x == 0]
            return len(nums)

  • 0
    M

    Why is it that when I try to shorten the code so it looks like the below, I can't get all the test cases correct?. Also, in OP's solution, how can you return len(nums) and have python know that you're actually referring to the nums[:] that was created?

    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            return len([nums[x] for x in range(len(nums)) if nums[x] != nums[x-1] or x == 0])
    

  • 0
    H
    This post is deleted!

  • 0
    H

    it allocate extra space, it doesn't change nums, so not works


  • 0
    L

    Seams like only nums[:] works instead of other variables.
    Would someone please be kind to explain?


  • 0
    B

    nums[:] will change the items in place.


Log in to reply
 

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