给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
提示:
- 1 <= nums.length <= 104
- -2^31 <= nums[i] <= 2^31 - 1
进阶:你能尽量减少完成的操作次数吗?
Python
双指针法:
1.左指针左边均为非零数;
2. 右指针左边直到左指针处均为零。
如果能想到这个就能写出来了,代码比较简单,如下:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# left=0 right = 0
# swap(nums[left],nums[right]) if nums[right]>0
left = 0
right=0
n=len(nums)
while right<n:
if nums[right]:
nums[left], nums[right]=nums[right],nums[left]
left+=1
right+=1
参考文献
283. 移动零