1. 题目

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

2. 解法

class Solution:
# 解法1
def moveZeroes(self, nums: List[int]) -> None:
index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[index] = nums[i]
index += 1
for i in range(index, len(nums)):
nums[i] = 0
return nums
# 解法2
def moveZeroes2(self, nums: List[int]) -> None:
start = 0
end = 1
while end < len(nums):
if nums[start] == 0 and nums[end] != 0:
nums[start], nums[end] = nums[end], nums[start]

if nums[start] == nums[end] == 0:
end += 1
continue

start += 1
end += 1