Leetcode 283. 移动零
1 题目描述(Leetcode题目链接)
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
2 题解
快慢指针来做,首先快慢指针都指向第一个位置,然后快指针向前移动,一旦遇到非零的数,就交换快慢指针的值,同时慢指针移动一步。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
j = 0
for i in range(length):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1