↓快轉到主要內容

Sliding-Window

LeetCode 4067: Longest Subarray With Restricted Pair Sums
·2 分鐘
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 4067 解題筆記:合法視窗的子陣列也合法,可以滑動;加入 x 時只要檢查跟 x 有關的三元組:x 當加數(x + y 在視窗裡)或 x 當和(x - y 在視窗裡)
LeetCode 1425: Constrained Subsequence Sum
·1 分鐘
LeetCode Hard Sliding-Window Dynamic-Programming Monotonic-Queue Heap Queue Array
LeetCode 1425 解題筆記:dp[i] = nums[i] + max(0, 前 k 個 dp 的最大值);前 k 個 dp 的最大值是滑動視窗最大值,用單調佇列 O(1) 取得
LeetCode 719: Find K-th Smallest Pair Distance
·2 分鐘
LeetCode Hard Binary-Search Two-Pointers Sliding-Window Sorting
LeetCode 719 解題筆記:對距離二分,用滑動窗口數「距離 <= mid 的 pair 數」
LeetCode 3835: Count Subarrays With Cost Less Than or Equal to K
·1 分鐘
LeetCode Medium Sliding-Window Monotonic-Queue Queue Array
LeetCode 3835 解題筆記:花費 = (最大 - 最小) × 長度,視窗變大只會變貴,所以可以滑動視窗數子陣列;視窗最大、最小值用兩個單調佇列維護
LeetCode 3323: Minimize Connected Groups by Inserting Interval
·1 分鐘
LeetCode Medium Sliding-Window Sorting Binary-Search Array
LeetCode 3323 解題筆記:先合併區間;新區間能把第 l 到 r 組連起來 ⇔ 第 r 組的起點 − 第 l 組的終點 <= k;滑動視窗找一次能連起來最多組
LeetCode 1984: Minimum Difference Between Highest and Lowest of K Scores
·1 分鐘
LeetCode Easy Sliding-Window Sorting Array
LeetCode 1984 解題筆記:排序後選出的 k 個一定是連續的一段;固定長度 k 的視窗,差是兩端相減
LeetCode 658: Find K Closest Elements
·2 分鐘
LeetCode Medium Two-Pointers Binary-Search Sliding-Window
LeetCode 658 解題筆記:雙指針從兩端縮成長度 k,或二分搜尋窗口的起點
LeetCode 1156: Swap For Longest Repeated Character Substring
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 1156 解題筆記:對每個字元 c 找「最多一個不是 c」的最長視窗,換進來的 c 必須來自別處,所以長度不能超過 c 的總數
LeetCode 2401: Longest Nice Subarray
·1 分鐘
LeetCode Medium Sliding-Window Bit-Manipulation Array
LeetCode 2401 解題筆記:兩兩 AND 為 0 ⇔ 每個 bit 最多被一個數用到;用一個 mask 記錄視窗用掉的 bit,衝突就縮左邊並把它的 bit 拿掉
LeetCode 992: Subarrays with K Different Integers
·1 分鐘
LeetCode Hard Sliding-Window Hash-Table Counting Array
LeetCode 992 解題筆記:「剛好 k 種」=「最多 k 種」−「最多 k - 1 種」,「最多」型的計數視窗每個右端加 right - left + 1
LeetCode 3306: Count of Substrings Containing Every Vowel and K Consonants II
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 3306 解題筆記:「剛好 k 個子音」不單調;改成「五個母音都有且子音至少 k 個」減「至少 k + 1 個」,兩個都是「至少」型的計數視窗
LeetCode 930: Binary Subarrays With Sum
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 930 解題筆記:「和剛好是 goal」= 「和最多 goal」−「和最多 goal - 1」;或用前綴和 + 雜湊表