Published:
Updated:

  • 파이썬 μ•Œκ³ λ¦¬μ¦˜ 책을 참고해도 계속 μ‹œκ°„ μ΄ˆκ³Όκ°€ λœ¬λ‹€..
    • 이 방법 뿐이야


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


Reference

Leave a comment