1. 程式人生 > >leetcode 283. 移動零(Easy) (陣列)

leetcode 283. 移動零(Easy) (陣列)

題目:       

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

示例:

輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]說明:
  1. 必須在原陣列上操作,不能拷貝額外的陣列。
  2. 儘量減少操作次數。

思路:

        首先,查詢list集合中0的個數n,然後把這些0都刪除掉。最後再在末尾新增上n個0。

程式碼:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        n = nums.count(0)
        for i in range(n):
            nums.remove(0)
        nums.extend([0]*n)