问题描述
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
给定一个数组编号,编写一个函数将所有0移到它的末尾,同时保持非零元素的相对顺序。
注意:
- 必须在不复制数组的情况下就地执行此操作。
- 最小化操作的总数。
输入:
[0,1,0,3,12]
输出:
[1,3,12,0,0]
Python 实现
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
non_zero_len = len(nums)
idx = 0
while idx < non_zero_len:
if nums[idx] == 0:
# Move the zero to the end of list.
nums.pop(idx)
nums.append(0)
non_zero_len -= 1
else:
idx += 1