题目描述:
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
思路:
使用两个指针:
i --> 当前遍历的元素下标
j --> 实际已移动不为0的元素下标
if i != j and nums[i] != 0:
nums[j] = nums[i]
nums[i] = 0
代码:
#
# @lc app=leetcode.cn id=283 lang=python3
#
# [283] 移动零
#
# @lc code=start
# 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
# 示例:
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
# 说明:
# 必须在原数组上操作,不能拷贝额外的数组。
# 尽量减少操作次数。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 数组长度
length = len(nums)
# 元素不是0时,j++
j = 0
for i in range(length):
if nums[i] != 0:
if j != i:
# 把不是0的元素依次移到前面
nums[j] = nums[i]
# 移动后的元素置为0
nums[i] = 0
# 只要出现元素不为0,j就加1
j += 1
print(nums)
# @lc code=end