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

LeetCode 3719: Longest Balanced Subarray I

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

基本資料
#

難易度: medium 第一次嘗試:2026-02-10

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

解題思路
#

條件是「不同的偶數個數 = 不同的奇數個數」。「不同的值」沒辦法直接用前綴和相減,但 n <= 1500,O(n²) 就夠了:

  • 固定左端點 i,右端點 j 往右擴。
  • 兩個集合分別放看過的奇數、偶數,每加一個數只更新一個集合,O(1)。
  • 兩個集合一樣大時更新答案。

如果 n 大很多(這題的 II 版),O(n²) 就不夠了,要換更進階的資料結構。

我的解法
#

class Solution:
    def longestBalanced(self, nums: List[int]) -> int:
        n, best = len(nums), 0
        for i in range(n):
            odd, even = set(), set()
            for j in range(i, n):
                (odd if nums[j] % 2 else even).add(nums[j])
                if len(odd) == len(even):
                    best = max(best, j - i + 1)
        return best

複雜度
#

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

要特別避免的錯誤
#

  • 數的是不同的值,重複出現的不能多算,所以要用集合。
  • 往右擴時增量更新,不要每次重算整個子陣列。

面試口說整理
#

n 只有 1500,我固定左端點往右擴,用兩個集合記錄看過的不同奇數和偶數,每一步 O(1) 更新,大小相同就更新最長長度。時間 O(n²)。

相關文章

LeetCode 930: Binary Subarrays With Sum
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 930 解題筆記:「和剛好是 goal」= 「和最多 goal」−「和最多 goal - 1」;或用前綴和 + 雜湊表
LeetCode 2875: Minimum Size Subarray in Infinite Array
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 2875 解題筆記:先拿掉 target // sum 個完整週期,剩下的餘數比一整圈小,一定能在兩份 nums 接起來的陣列裡用滑動視窗找到
LeetCode 1248: Count Number of Nice Subarrays
·2 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 1248 解題筆記:「剛好 k 個奇數」不單調,改成「最多 k 個」減「最多 k - 1 個」;或用前綴和 + 雜湊表
LeetCode 3810: Minimum Operations to Reach Target Array
·1 分鐘
LeetCode Medium Greedy Hash-Table Array
LeetCode 3810 解題筆記:一次操作會把某個值的所有位置都改對,所以答案是不相等的位置上有幾種不同的值
LeetCode 1838: Frequency of the Most Frequent Element
·1 分鐘
LeetCode Medium Sliding-Window Sorting Greedy Prefix-Sum Binary-Search Array
LeetCode 1838 解題筆記:排序後,把視窗裡的數都加到 nums[right] 的花費是 nums[right] × 長度 − 視窗總和;花費 > k 就縮左邊
LeetCode 2271: Maximum White Tiles Covered by a Carpet
·1 分鐘
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 2271 解題筆記:地毯的左端放在某段白磚的起點一定不會更差;排序後用雙指針,完整蓋住的段累加,最後一段只算部分