150強訪談

滑動視窗最大值

“滑動視窗最大值”問題的詳細指南和 Python 實作。

問題陳述

給定一個整數陣列 nums 和一個整數 k ,表示滑動視窗的大小,該視窗從陣列的最左邊移動到最右邊。您只能在視窗中看到 k 數字。每次滑動視窗右移一個位置。

傳回每個滑動視窗中的最大值。

寫一個函數 maxSlidingWindow(nums: List[int], k: int) -> List[int]

約束條件
  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= len(nums)

範例

Example 1
Input
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output
[3, 3, 5, 5, 6, 7]
Explanation

Window [1,3,-1] max=3, [3,-1,-3] max=3, [-1,-3,5] max=5, [-3,5,3] max=5, [5,3,6] max=6, [3,6,7] max=7.

Example 2
Input
nums = [1], k = 1
Output
[1]
Explanation

Single element window, max is 1.

Need a Hint?
考慮使用滑動視窗特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。