Python short in-place solution with comments.


  • 32
    C
    # in-place
    def moveZeroes(self, nums):
        zero = 0  # records the position of "0"
        for i in xrange(len(nums)):
            if nums[i] != 0:
                nums[i], nums[zero] = nums[zero], nums[i]
                zero += 1

  • 0
    Z

    Finally I found someone posted this standard in-place two-pointer :)


  • 1
    F

    Haha, this is the real pythonic solution using 2 pointers instead of those C++, Java crap!!!! REPPED!


  • 0
    X

    This is a smart solution!!!


  • 0
    Y

    is my code better or worse on operation numbers? or it is equally good? comments welcome!

    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            if len(nums)==1:                #single number, return  
                return
            for i in range(len(nums)-1):    #only scan to the second last one
                if nums[i]==0:              #find the zero position
                    j=i+1
                    while nums[j]==0 and j<len(nums)-1: #get the next non-zero number
                        j+=1
                    if j==len(nums)-1 and nums[j]==0:   #if hit boundary and the boundary number is zero,return 
                        return 
                    else:                               
                        nums[i],nums[j]=nums[j],nums[i] #exchange
            return 
    

  • 2
    T

    class Solution(object):
    def moveZeroes(self, nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    for num in nums:
    if num == 0:
    nums.remove(num)
    nums.append(num)
    return


  • 1
    N

    @totalawesomeness 代码要求不需要return


  • 0
    M
    This post is deleted!

  • 0
    F

    add a if statement to avoid unnecessary assignments.

    zero = 0  # records the position of "0"
    for i in xrange(len(nums)):
        if nums[i] != 0:
            if zero != i: # avoid unnecessary assignments
                nums[i], nums[zero] = nums[zero], nums[i]
            zero += 1
    

  • 0
    I

    @fangzq88 How zero keeps incrementing by one without stopping?
    Can please explain?


  • 0
    F

    @iMems The basic idea is two-pointer algorithm, and this is a concise solution. When exchanging the values of nums[i] and nums[zero], the zero records the index of first 0 in nums and i is the index of first non-zero item after index zero. The control flow will be clear if you study this mehtod with a example, for instance [0,1,0,3,12].


  • 0
    D

    @totalawesomeness Is this still considered "in place"? You're modifying the list size.


Log in to reply
 

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