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

LeetCode 3804: Number of Centered Subarrays

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

基本資料
#

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

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

解題思路
#

n <= 500,枚舉所有子陣列是 O(n²) 個。固定左端點 i、右端點 j 往右擴:

  • 總和邊擴邊加。
  • 子陣列裡有哪些值,用一個集合邊擴邊加,查詢 O(1)。

我的解法
#

我當時用 curr_sum in nums[i: j + 1] 檢查,每次都切一段再線性搜尋,整體 O(n³),跑了 2.8 秒。改成增量維護的集合:

class Solution:
    def centeredSubarrays(self, nums: List[int]) -> int:
        n, res = len(nums), 0
        for i in range(n):
            seen, total = set(), 0
            for j in range(i, n):
                total += nums[j]
                seen.add(nums[j])
                res += total in seen
        return res

複雜度
#

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

要特別避免的錯誤
#

  • 不要每次都切片再搜尋,那是 O(n) 的額外成本。

面試口說整理
#

我固定左端點往右擴,同時維護總和和看過的值的集合,總和在集合裡就算一個置中的子陣列。每次擴張 O(1),總共 O(n²)。

相關文章

LeetCode 2958: Length of Longest Subarray With at Most K Frequency
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2958 解題筆記:「求最長」的滑動視窗,剛加入的數字出現超過 k 次就縮左邊
LeetCode 2653: Sliding Subarray Beauty
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2653 解題筆記:值域只有 -50 到 50,固定視窗用計數陣列維護,每個視窗從 -50 往上累加找第 x 小的負數
LeetCode 2831: Find the Longest Equal Subarray
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Binary-Search Array
LeetCode 2831 解題筆記:對每個值,把它出現的位置列出來;在位置列表上滑動視窗,要刪的數量 = 位置跨度 − 這個值的個數
LeetCode 3795: Minimum Subarray Length With Distinct Sum At Least K
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 3795 解題筆記:求最短的可變視窗;同一個值只算一次,記錄每個值最後出現的位置,左邊界移出的是最後一次出現才扣掉
LeetCode 2461: Maximum Sum of Distinct Subarrays With Length K
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2461 解題筆記:固定長度 k 的視窗,不同值的個數剛好等於 k 才代表全部不重複
LeetCode 3679: Minimum Discards to Balance Inventory
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 解題筆記:規則已經決定哪些要丟,直接模擬;長度 w 的視窗只計算「留下來」的到貨,被丟掉的離開視窗時不能再扣