题目:
给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相>对顺序。
例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。
注意事项:
- 必须在原数组上操作,不要为一个新数组分配额外空间。
- 尽量减少操作总数。
题解:
count记录0的个数。每次将列表首个pop,如果是0,则count++;否则append到列表末尾。遍历完在list末尾添加count个0
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count = 0
for i in range(0, len(nums)):
x = nums.pop(0)
if x:
nums.append(x)
else:
count += 1
while count:
nums.append(0)
count -= 1