Simple python code O(N)


  • 2
    H
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        k=0 #step1:move all none zero numbers to the front
        for num in nums:
            if num!=0:
                nums[k]=num
                k+=1
        nums[k:]=[0]*(len(nums)-k) #step2: set the rest of the list to be zero

  • 0
    S

    Doesn't enumerate(nums) functionally create a copy of nums for the enumerator, violating the requirement that the solution be in-place?


  • 0
    H

    i shouldn't use enumerate.
    the code is changed. how is it now?


  • 1

    No, enumerate doesn't create a copy. Demo:

    >>> a = [4, 5]
    >>> e = enumerate(a)
    >>> a[:] = [6, 7, 8]
    >>> list(e)
    [(0, 6), (1, 7), (2, 8)]
    

  • 0
    S

    Well no that isn't an exact copy, but what I meant is that enumerate creates a separate object that occupies additional memory. So using enumerate would not be in-place to my understanding.


  • 0
    S

    And @Hendrik_van_Oost, I believe your updated code looks good to me.


  • 0

    @Skyyan Even k=0 creates a new object that occupies additional memory. And [0]*(len(nums)-k) might even create a new list as big as the input.

    Using enumerate is fully ok (except that it was misused here because the index wasn't used (I'm looking at google's cache to see the original)).


Log in to reply
 

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