在 Python 中移動零


假設我們有一個數組來容納一些數字。有非零值以及零值。因此,我們必須將所有零傳送到右側,而不會更改其他數字的相對順序。因此,如果陣列類似於 [0, 1, 5, 0, 3, 8, 0, 0, 9],則最終陣列將為 [1, 5, 3, 8, 9, 0, 0, 0, 0]

要解決此問題,我們將執行以下步驟:

  • 假設 index = 0
  • i 從 0 到 A 的長度
    • 如果 A[i] != 0,則
      • A[index] := A[i]
      • index := index + 1
  • i 從 index 到 A 的長度
    • A[i] = 0

示例

讓我們檢視以下實現以獲得更好的理解:

 即時演示

class Solution(object):
   def moveZeroes(self, nums):
      """
      :type nums: List[int]
      :rtype: None Do not return anything, modify nums in-place instead.
      """
      insert_index = 0
      for i in range(len(nums)):
         if nums[i] != 0:
            nums[insert_index]=nums[i]
            insert_index+=1
      for i in range(insert_index,len(nums)):
         nums[i]=0
nums = [0,1,5,0,3,8,0,0,9]
ob1 = Solution()
ob1.moveZeroes(nums)
print(nums)

輸入

nums = [0,1,5,0,3,8,0,0,9]

輸出

[1,5,3,8,9,0,0,0,0]

更新日期: 2020 年 4 月 28 日

933 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.