Solution 1 - Swap
-
If the num is not 0, move forward if possible, i.e.
zero < i, nums[zero] = nums[i]
-
If the num is 0, leave it and search for the number to ‘fill in’ it.
-
The key point is
zero < i
becausezero
is not updated at each iteration.
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
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
Solution 2 - Re-assign
-
Get the index of all zeros.
-
Copy the other numbers to the beginning of the array.
-
Assign the last few positions 0 value.
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count=nums.count(0)
nums[:]=[i for i in nums if i != 0]
nums+=[0]*count
PREVIOUSMajority Element
NEXTSingle Number