↓快轉到主要內容
  1. LeetCode/

LeetCode 283: Move Zeroes

·1 分鐘· ·
LeetCode Easy Array Two-Pointers
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-23

  • 提交紀錄:Accepted ×2 → Wrong Answer ×2 → Accepted ×2

解題思路
#

left 是下一個非零數要放的位置(Two Pointers 模板五)。掃到非零的 nums[right] 就跟 nums[left] 交換,left += 1。非零數的相對順序保持不變,零都被換到後面。

我的嘗試
#

2022 年就 AC 了;2025 年重寫時把 left += 1 寫在 if 外面,每一步都前進,等於沒有移動,例如 [0, 1] 還是 [0, 1]。

正確解法
#

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        left = 0
        for right in range(len(nums)):
            if nums[right] != 0:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • left += 1 要放在 if 裡面,只有寫入非零數時才前進。

面試口說整理
#

我用 left 記下一個非零數要放的位置,遇到非零數就跟它交換並前進,零就會被擠到後面。時間 O(n)、空間 O(1)。

相關文章

LeetCode 27: Remove Element
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 27 解題筆記:寫入指標只寫不等於 val 的數,最後回傳寫入的個數
LeetCode 26: Remove Duplicates from Sorted Array
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 26 解題筆記:快慢指針原地覆寫,慢指針指向下一個要寫的位置;遇到跟前一個寫入的值不同才寫
LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 350: Intersection of Two Arrays II
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 解題筆記:保留重複次數的交集,Counter 相交(&)取兩邊次數的較小值
LeetCode 268: Missing Number
·1 分鐘
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 解題筆記:0 到 n 的總和減掉陣列總和就是缺的那個;缺的可能是 0
LeetCode 344: Reverse String
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 344 解題筆記:左右指針交換後往中間走,原地反轉