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

LeetCode 35: Search Insert Position

·1 分鐘· ·
LeetCode Easy Array Binary-Search
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 → Runtime Error ×2 → Accepted → Wrong Answer → Time Limit Exceeded → Wrong Answer ×2 → Runtime Error → Accepted ×2

解題思路
#

插入的位置就是「第一個 >= target 的 index」,也就是 lower bound(Binary Search 模板一)。用半開區間 [l, r):nums[mid] < target 時答案在右邊 l = mid + 1,否則 mid 可能就是答案,r = mid。

我的嘗試
#

這題提交了 12 次,主要是區間寫法混在一起:

  • 一開始忘了寫回傳值、用 / 算 mid(TypeError)。
  • 2022 年 11 月重寫時用了半開區間 right = len(nums),卻寫 right = mid - 1,把可能的答案跳過了。例如 [0, 7]、target = 5:答案 1,回傳 0。

正確解法
#

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums)
        while l < r:
            mid = (l + r) // 2
            if nums[mid] < target:
                l = mid + 1
            else:
                r = mid
        return l

複雜度
#

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

要特別避免的錯誤
#

  • 區間寫法不能混用:r = len(nums) 的半開區間要配 while l < r 和 r = mid。

面試口說整理
#

答案是第一個不小於目標的位置,所以我用半開區間做 lower bound:中間比目標小就往右,否則把右界縮到中間。最後的 l 就是答案。時間 O(log n)。

相關文章

LeetCode 27: Remove Element
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 27 解題筆記:寫入指標只寫不等於 val 的數,最後回傳寫入的個數
LeetCode 66: Plus One
·1 分鐘
LeetCode Easy Array Math
LeetCode 66 解題筆記:從最後一位往前加一,遇到 9 變 0 繼續進位,全部都是 9 時前面補 1
LeetCode 26: Remove Duplicates from Sorted Array
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 26 解題筆記:快慢指針原地覆寫,慢指針指向下一個要寫的位置;遇到跟前一個寫入的值不同才寫
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 有沒有出現過;先查再存,同一個元素才不會用兩次
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 找不到會丟例外