問題描述
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