题目描述
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
一、同向双指针
1. 思路
- 定义填充指针、移动指针都从index为0开始
- 移动指针遇到非0数,则将该数填充到填充指针位置
- 每次都移动一次移动指针
2.代码
class Solution:
def moveZeroes(self, nums) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 定义填充指针、移动指针都从index为0开始
fill_point, move_point = 0, 0
while move_point < len(nums):
# 当移动指针指向的数不为0时,将填充指针位置填充成移动指针的数,并且移动填充指针
if nums[move_point] != 0:
nums[fill_point] = nums[move_point]
fill_point += 1
# 每次循环都要移动移动指针
move_point += 1
# 最后将剩余位置填充为0
for i in range(fill_point, len(nums)):
nums[i] = 0