1. 程式人生 > >LeetCode(283. 移動零)

LeetCode(283. 移動零)

lee range 編寫 pytho 覆蓋 etc mod 描述 lis

問題描述

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

示例:

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

說明:

  1. 必須在原數組上操作,不能拷貝額外的數組。
  2. 盡量減少操作次數。

解決方案

1.最快的原地置換

class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        zero = 0
        for i in range(len(nums)):
            if not nums[i] == 0 and zero <= i:
                nums[i], nums[zero] = nums[zero], nums[i]
                zero += 1

2.使用remove+append

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

3.先覆蓋,再寫入0

class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        count = 0
        for i in range(0, len(nums)):
            if (nums[i] != 0):
                nums[count] = nums[i]
                count += 1
        for j in range(count, len(nums)):
            nums[j] = 0
        

LeetCode(283. 移動零)