[Python] 힙(heap)

2023. 5. 4. 13:01
import heapq

heap = []
nums = [3, 7, 2, 9, 1]

# 최소 힙 (1,2,3,7,9)
for i in nums:
    heapq.heappush(heap, i)
 
print(heap)
# 1,2,3,9,7 (push로 오름차순 정렬 보장은 안되지만 첫번째 원소가 가장 작음을 보장)
# 두번째로 작은 원소 : heappop() 가장 작은 원소를 삭제 후 heap[0] 새로운 최소값에 접근해야 함
 
for i in range(len(heap)):
    print(heapq.heappop(heap))
 
# ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
 
 

# 최대 힙 (9,7,3,2,1)
for i in nums:
    heapq.heappush(heap, -i)
 
print(heap)
 
for i in range(len(heap)):
    print(-heapq.heappop(heap))