파이썬의 heapq는 **최소 힙(min-heap)**을 기본으로 제공하며, 이를 통해 최솟값을 빠르게 조회하고 삭제하는 것이 가능합니다. 각 연산의 시간 복잡도와 함께 주요 연산에 대해 설명드리겠습니다. 최대 힙을 구현하기 위해서는 입력값과 출력값에 -1을 곱하여 문제를 해결할 수 있다.


주요 함수

heapq.heappush(heap, item), 삽입 연산

import heapq

heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 1)
heapq.heappush(heap, 5)
print(heap)  # [1, 10, 5]

heapq.heappop(heap), 제거 연산

smallest = heapq.heappop(heap)
print(smallest)  # 1
print(heap)  # [5, 10]

heapq.heappushpop(heap, item), 삽입후 제거 연산

smallest = heapq.heappushpop(heap, 2)
print(smallest)  # 1
print(heap)  # [2, 3, 4, 9, 5]

heapq.heapreplace(heap, item), 제거후 삽입 연산