# inplace
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
Python short inplace solution with comments.

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 inplace 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 nonzero 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



@iMems The basic idea is twopointer algorithm, and this is a concise solution. When exchanging the values of
nums[i]
andnums[zero]
, thezero
records the index of first 0 innums
andi
is the index of first nonzero item after indexzero
. The control flow will be clear if you study this mehtod with a example, for instance [0,1,0,3,12].

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