- 分類:string
- 時(shí)間復(fù)雜度: O(n)
- 空間復(fù)雜度: O(1)
283. Move-Zeroes
給定一個(gè)數(shù)組 nums,編寫(xiě)一個(gè)函數(shù)將所有 0 移動(dòng)到數(shù)組的末尾,同時(shí)保持非零元素的相對(duì)順序。
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
來(lái)源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/move-zeroes 著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
必須在原數(shù)組上操作,不能拷貝額外的數(shù)組。 盡量減少操作次數(shù)。
代碼1:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
not_zero_index = 0
for i in range(len(nums)):
if nums[i]!=0:
nums[not_zero_index]=nums[i]
not_zero_index+=1
for i in range(not_zero_index,len(nums)):
nums[i]=0
討論:
1.這題,突如其來(lái)的熟悉感。。。我在umich時(shí)候的career fair做到過(guò)這個(gè)題目??傊€是挺easy的(希望不要被自己打臉)