给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。
要求
1.必须在原数组上操作,不能拷贝额外的数组
2.尽量减少操作次数
3.注意时间空间复杂度
输入:
0 1 0 3 12
输出:
1 3 12 0 0
def moveZeroes(nums):
non_zero_index = 0
# 遍历数组
for current in range(len(nums)):
# 当遇到非零元素时
if nums[current] != 0:
# 将非零元素放置在 non_zero_index 指向的位置
nums[non_zero_index] = nums[current]
non_zero_index += 1
# 将 non_zero_index 后面的所有元素置为 0
while non_zero_index < len(nums):
nums[non_zero_index] = 0
non_zero_index += 1
# 示例用法
nums = [0, 1, 0, 3, 12]
moveZeroes(nums)
print(nums) # 输出:[1, 3, 12, 0, 0]