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

LeetCode 3818: Minimum Prefix Removal to Make Array Strictly Increasing

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

基本資料
#

難易度: medium 第一次嘗試:2026-01-25

  • 提交紀錄:Accepted(一次通過)

解題思路
#

留下來的一定是一段後綴,而且要嚴格遞增。後綴越長、刪的前綴越短,所以從右往左走,只要 nums[i - 1] < nums[i] 就繼續(Array 模板一)。停下來的位置 i 就是要刪的長度。

我的解法
#

class Solution:
    def minimumPrefixLength(self, nums: List[int]) -> int:
        i = len(nums) - 1
        while i > 0 and nums[i - 1] < nums[i]:
            i -= 1
        return i

我當時寫成 while ... else: return right,因為迴圈沒有 break,else 一定會執行,結果一樣;直接回傳比較清楚。

複雜度
#

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

要特別避免的錯誤
#

  • 嚴格遞增,相等也要停。

面試口說整理
#

留下的一定是嚴格遞增的後綴,所以我從右往左走到第一個不遞增的位置,它的 index 就是要刪的前綴長度。時間 O(n)。

相關文章

LeetCode 1574: Shortest Subarray to be Removed to Make Array Sorted
·1 分鐘
LeetCode Medium Two-Pointers Binary-Search Array Monotonic-Stack
LeetCode 1574 解題筆記:留下來的一定是「非遞減前綴 + 非遞減後綴」;先找出最長前綴和後綴,再用雙指針把兩段接起來
LeetCode 1877: Minimize Maximum Pair Sum in Array
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array
LeetCode 1877 解題筆記:排序後最小配最大、次小配次大,對撞指針取配對和的最大值
LeetCode 2105: Watering Plants II
·1 分鐘
LeetCode Medium Two-Pointers Simulation Array
LeetCode 2105 解題筆記:Alice 從左、Bob 從右,對撞指針模擬澆水;相遇在同一株時由水比較多的人澆
LeetCode 2401: Longest Nice Subarray
·1 分鐘
LeetCode Medium Sliding-Window Bit-Manipulation Array
LeetCode 2401 解題筆記:兩兩 AND 為 0 ⇔ 每個 bit 最多被一個數用到;用一個 mask 記錄視窗用掉的 bit,衝突就縮左邊並把它的 bit 拿掉
LeetCode 930: Binary Subarrays With Sum
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 930 解題筆記:「和剛好是 goal」= 「和最多 goal」−「和最多 goal - 1」;或用前綴和 + 雜湊表
LeetCode 2962: Count Subarrays Where Max Element Appears at Least K Times
·1 分鐘
LeetCode Medium Sliding-Window Array
LeetCode 2962 解題筆記:「至少 k 次」的計數視窗:最大值出現 k 次時一直縮左邊,縮完後左端在 [0, left) 的子陣列都合法,count += left