题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
输入: nums = [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.
"""
for i in range(len(nums)):
if nums[i] == 0:
nums.remove(nums[i])
nums.append(0)
# 遍历 nums 遇到不为 0 的数,不断的两两交换
idx = 0
for explorer in range(len(nums)):
if nums[explorer] != 0:
nums[anchor], nums[explorer] = nums[explorer], nums[idx]
idx += 1
思路
遍历 nums 遇到不为 0 的数,不断的两两交换,这个思路着实难理解