# 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.

correct me if I'm wrong but I just tested with an input of
[1, 0, 1]
and the result is still[1, 0, 1]
when is suppose to be[1, 1, 0]
I tested in python 3 btw, my code below works:
def moveZeroes(nums): i = 0 for j in range(1, len(nums)): print(i, j) if nums[j] != 0 and nums[i] == 0: nums[i], nums[j] = nums[j], nums[i] i += 1 if nums[i] != 0: i += 1 return nums

Wouldn't swapping two values count as two operations? For example running this against the array
[0, 8, 0, 9]
would require four operations total (two swaps):nums[0] = 8 nums[1] = 0 nums[1] = 9 nums[3] = 0
One of these steps, setting nums[1] = 0, is completely unnecessary. Here's a solution that requires only 3 operations on the same array:
def moveZeroes(self, nums): place = 0 # records the position of "0" for x in nums: if x != 0: nums[place] = x # One operation total. place += 1 for index in range(place, len(nums)): if nums[index] != 0: # At most one operation per step. nums[index] = 0
