給定一個數(shù)組 nums,編寫一個函數(shù)將所有 0 移動到數(shù)組的末尾,同時保持非零元素的相對順序。
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說明:
必須在原數(shù)組上操作,不能拷貝額外的數(shù)組。
盡量減少操作次數(shù)。
解答:
此處我們需要了解python的三種刪除方式,del list[index] 刪除對應(yīng)index的元素,index自動重排序;list.remove(obj) 刪除對應(yīng)值為obj的元素,不改index;list.pop(index)刪除制定index的元素。
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
org = len(nums)
index=0
for i in range(org):
'''i 只是用于記錄操作次數(shù),和index毫無關(guān)系。
remove是刪除list中第一次出現(xiàn)的某個元素,
del 是刪除對應(yīng)index的元素'''
if nums[index]==0:
nums.append(0)
del nums[index]
else:
index+=1