題目:
283.移動零:
給定一個陣列 nums,撰寫一個函式將所有 0 移動到陣列的末尾,同時保持非零元素的相對順序,
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說明:
- 必須在原陣列上操作,不能拷貝額外的陣列,
- 盡量減少操作次數,
解題思路
list.remove() 移除串列中第一個匹配項,list.append() 在串列末尾添加元素,
遍歷串列,每查找到串列中的0元素,就將其移除,并計數,遍歷結束后,串列僅剩保持原順序的非0元素,然后再串列末尾添加相應個數的0元素,
代碼1:while回圈
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
count = 0
while 0 in nums:
count += 1
nums.remove(0)
while count != 0:
nums.append(0)
count -= 1
代碼2:for回圈
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = nums.count(0)
for i in range(n):
nums.remove(0)
nums.append(0)
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/240061.html
標籤:python
