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

LeetCode 27: Remove Element

·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-05-11

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

解題思路
#

寫入指標 k(Two Pointers 模板五):每個不等於 val 的數寫到 nums[k],k += 1。前 k 個就是保留下來的,順序不重要。

我的嘗試
#

第一版的條件寫成 v != nums(拿數字跟整個 list 比),永遠成立,等於沒有刪任何東西,例如 [2]、val = 2 回傳 1。

正確解法
#

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        k = 0
        for x in nums:
            if x != val:
                nums[k] = x
                k += 1
        return k

複雜度
#

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

要特別避免的錯誤
#

  • 條件比的是 val。

面試口說整理
#

我用寫入指標,把不等於 val 的數依序寫到前面,最後回傳寫入的個數。時間 O(n)、空間 O(1)。

相關文章

LeetCode 26: Remove Duplicates from Sorted Array
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 26 解題筆記:快慢指針原地覆寫,慢指針指向下一個要寫的位置;遇到跟前一個寫入的值不同才寫
LeetCode 28: Find the Index of the First Occurrence in a String
·1 分鐘
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 解題筆記:在每個起點比對 needle,或直接用 str.find;index 找不到會丟例外
LeetCode 35: Search Insert Position
·1 分鐘
LeetCode Easy Array Binary-Search
LeetCode 35 解題筆記:找第一個 >= target 的位置(lower bound);半開區間 [l, r) 要配 r = mid,不能寫 r = mid - 1
LeetCode 66: Plus One
·1 分鐘
LeetCode Easy Array Math
LeetCode 66 解題筆記:從最後一位往前加一,遇到 9 變 0 繼續進位,全部都是 9 時前面補 1
LeetCode 14: Longest Common Prefix
·1 分鐘
LeetCode Easy Array String Trie
LeetCode 14 解題筆記:用最短的字串當上限,逐個位置檢查所有字串是否相同,第一個不同的位置就是答案的長度
LeetCode 1: Two Sum
·1 分鐘
LeetCode Easy Array Hash-Table
LeetCode 1 解題筆記:一邊掃一邊把看過的數存進雜湊表,查 target - x 有沒有出現過;先查再存,同一個元素才不會用兩次