2019-02-27
閱讀量:
773
給定數(shù)組編寫一個(gè)函數(shù)將所有 0 移動(dòng)到數(shù)組的末尾
給定一個(gè)數(shù)組nums
,編寫一個(gè)函數(shù)將所有0
移動(dòng)到數(shù)組的末尾,同時(shí)保持非零元素的相對(duì)順序。
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說明:
- 必須在原數(shù)組上操作,不能拷貝額外的數(shù)組。
- 盡量減少操作次數(shù)。
答:我的思路是先刪除所有的0,記住一共刪除了多少。最后在數(shù)組末尾添加同樣數(shù)量的0.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
count_flags = 0
while 0 in nums:
count_flags += 1
nums.pop(nums.index(0))
nums.extend([0 for _ in range(count_flags)])






評(píng)論(0)


暫無數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論
0條評(píng)論