λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
🧩 Algorithm/μš°μ„ μˆœμœ„ 큐

νž™(Heap) μ‘μš©λ°©λ²•

by HelloRabbit 2023. 2. 10.
728x90

Goal

1. νž™μ˜ μ‘μš© 방법 μ•Œμ•„λ³΄κΈ°

 

ν•¨μˆ˜ heappop() μ΄μš©ν•˜κΈ°

μ€‘μš”ν•œ 점은 heapq.heappop(heap)은 항상 heapμ—μ„œ κ°€μž₯ μž‘μ€ 값을 λ°˜ν™˜ν•œλ‹€λŠ” 것이닀.

 

μž‘μ€ 수 ➑️ 큰 수

μ•„λž˜μ™€ 같이 1μ—μ„œ 5κΉŒμ§€μ˜ μˆ«μžκ°€ μžˆμ„ λ•Œ heap을 μ΄μš©ν•˜λ©΄ κ°€μž₯ μž‘μ€ μˆ˜λΆ€ν„° μˆœμ„œλŒ€λ‘œ λ½‘λŠ” 것은 κ°„λ‹¨ν•˜λ‹€.

import heapq

arr = [1, 2, 3, 4, 5]

heap = []
for num in arr:
    heapq.heappush(heap, num)

for i in range(len(heap)):
    print(heapq.heappop(heap))	# 좜λ ₯: 1 2 3 4 5

 

큰 수 ➑️ μž‘μ€ 수

거꾸둜 νž™μ„ μ΄μš©ν•΄μ„œ 큰 μˆ˜λΆ€ν„° μˆœμ„œλŒ€λ‘œ λ½‘λŠ” 것도 κ°€λŠ₯ν•˜λ‹€.

import heapq

arr = [1, 2, 3, 4, 5]

heap = []
for num in arr:
    heapq.heappush(heap, -num)	# λ§ˆμ΄λ„ˆμŠ€ν•œ 숫자λ₯Ό λ„£μ–΄μ€€λ‹€ => [-1, -2, -3, -4, -5]

for i in range(len(heap)):
    print(-heapq.heappop(heap))	# 좜λ ₯ν•  λ•Œλ„ λ‹€μ‹œ λ§ˆμ΄λ„ˆμŠ€λ₯Ό 더해쀀닀 => 좜λ ₯: 5 4 3 2 1

λ§ˆμ΄λ„ˆμŠ€ κ°’μœΌλ‘œ heap에 λ„£μ—ˆκΈ° λ•Œλ¬Έμ— 이제 κ°€μž₯ μž‘μ€ μˆ˜λŠ” 1이 μ•„λ‹ˆλΌ -5κ°€ λœλ‹€.

이제 heappop(heap)을 ν•˜λ©΄ κ°€μž₯ μž‘μ€ 수인 -5κ°€ λ°˜ν™˜λ˜κ³ , 이 μˆ˜μ— λ‹€μ‹œ λ§ˆμ΄λ„ˆμŠ€λ₯Ό ν•΄μ£Όλ©΄ μ›λž˜μ˜ 5κ°€ 됨으둜 큰 μˆ˜λΆ€ν„° 뽑을 수 있게 λœλ‹€.

 

 

 

λŒ“κΈ€