[LeetCode] 239. Sliding Window Maximum (Python)
python, algorithms, array, queue, sliding-window, heap, priority-queue, monotonic-queue
Tags: algorithms, array, heap, monotonic-queue, priority-queue, python, queue, sliding-window
Categories: LeetCode
- νμ΄μ¬ μκ³ λ¦¬μ¦ μ±
μ μ°Έκ³ ν΄λ κ³μ μκ° μ΄κ³Όκ° λ¬λ€..
- μ΄ λ°©λ² λΏμ΄μΌ
Solution
import heapq
from typing import List
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
answer = []
# μ¬λΌμ΄μ± μλμ° κ°λ€μ μ μ₯
max_heap = []
for i, num in enumerate(nums):
# νμμ κ°μ₯ ν° κ°μ΄ 루νΈμ μμΉνκ² λ¨
heapq.heappush(max_heap, (-num, i))
if i >= k - 1:
current_i = max_heap[0][1]
# μλμ°λ₯Ό μ΄λνλ©΄μ μλμ°μμ λ²μ΄λλ κ°μ νμμ μ κ±°
while current_i < i - k + 1:
heapq.heappop(max_heap)
# νμ 루νΈμ μλ κ°μ΄ νμ¬ μλμ° λ΄μ μ΅λκ°μ΄ λ¨
current_num = max_heap[0][0]
answer.append(-current_num)
return answer
Leave a comment