1:题目描述(力扣)
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
2:解题思路
使用双指针解法
第一步:创建左右指针,左指针指向当前已经处理好的新数组(即最终结果的数组)的尾部,右指针指向待处理数组的头部。初始化左右指针的值,都从下标0开始,left,right=0,0
第二步:不断向右移动右指针,判断当前右指针对应的数组元素是否等于0,不等于0,则将左右指针对应的值进行互换,并移动左指针
以示例1为例:
代码展示:
class Solution:
def moveZeroes(self, nums):
"""
Do not return anything, modify nums in-place instead.
"""
left, right = 0, 0
while right < len(nums):
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
return nums