1. 程式人生 > >【leetcode 簡單】 第七十六題 移動零

【leetcode 簡單】 第七十六題 移動零

移動 mov spa urn mod 保持 odi 末尾 any

給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。

示例:

輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]

說明:

  1. 必須在原數組上操作,不能拷貝額外的數組。
  2. 盡量減少操作次數。
class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        i 
= 0 for test in nums: if test != 0: nums[i] = test i+=1 for i in range(i,len(nums)): nums[i]=0

【leetcode 簡單】 第七十六題 移動零