class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = nums.count(0)
for i in range(n):
nums.remove(0)
nums.extend([0]*n)
return nums
Method 2
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
#非0往前移动
index = 0
for num in nums:
if num != 0:
nums[index] = num
index += 1
#末尾补0
for i in range(index, len(nums)):
nums[i] = 0
return nums
Method 3
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
slow = fast = 0
while fast < len(nums):
if nums[fast] != 0:
nums[fast], nums[slow] = nums[slow], nums[fast]
slow += 1
fast += 1