ํ์ด์ฌ ํ ์๋ฃ๊ตฌ์กฐ
ํ์ด์ฌ heapq ๋ชจ๋์ heapq (priority queue) ์๊ณ ๋ฆฌ์ฆ์ ์ ๊ณตํ๋ค.
๋ชจ๋ ๋ถ๋ชจ ๋ ธ๋๋ ๊ทธ์ ์์ ๋ ธ๋๋ณด๋ค ๊ฐ์ด ์๊ฑฐ๋ ํฐ ์ด์งํธ๋ฆฌ(binary tree) ๊ตฌ์กฐ์ธ๋ฐ, ๋ด๋ถ์ ์ผ๋ก๋ ์ธ๋ฑ์ค 0์์ ์์ํด k๋ฒ์งธ ์์๊ฐ ํญ์ ์์ ์์๋ค(2k+1, 2k+2) ๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ์ต์ ํ์ ํํ๋ก ์ ๋ ฌ๋๋ค.
heapq๋ ๋ด์ฅ ๋ชจ๋๋ก ๋ณ๋์ ์ค์น ์์ ์์ด ๋ฐ๋ก ์ฌ์ฉํ ์ ์๋ค.
ํ ํจ์ ํ์ฉํ๊ธฐ
- heapq.heappush(heap, item) : item์ heap์ ์ถ๊ฐ
- heapq.heappop(heap) : heap์์ ๊ฐ์ฅ ์์ ์์๋ฅผ pop & ๋ฆฌํด. ๋น์ด ์๋ ๊ฒฝ์ฐ IndexError๊ฐ ํธ์ถ๋จ.
- heapq.heapify(x) : ๋ฆฌ์คํธ x๋ฅผ ์ฆ๊ฐ์ ์ผ๋ก heap์ผ๋ก ๋ณํํจ (in linear time, O(N) )
์์
import heapq
heap = []
heapq.heappush(heap, 50)
heapq.heappush(heap, 10)
heapq.heappush(heap, 20)
print(heap)
[10, 50, 20]
import heapq
heap = []
heapq.heappush(heap, 4)
heapq.heappush(heap, 3)
heapq.heappush(heap, 2)
heapq.heappush(heap, 5)
heapq.heappush(heap, 1)
print(heap)
[1, 2, 3, 5, 4]
'Algorithm > Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java] int ํ(Primitive type)๋ฐฐ์ด์ List๋ก + ๋ด๋ฆผ์ฐจ์( Stream ์ฌ์ฉ) (0) | 2022.11.22 |
---|---|
[Java] ์๋ฐ์ ๋ฐ์ดํฐ ํ์ (primitive type, reference type) (0) | 2022.11.22 |
Python Deque(Double-Ended Queue) + Stack, Queue ๊ฐ๋จ๊ฐ๋ (0) | 2021.12.23 |
Arrays.sort ( ์ฌ์ ์์๋๋ก ์ ๋ ฌํด์ฃผ๋ ๋ฉ์๋) (0) | 2021.10.25 |
String, StringBuffer/ StringBuilder (0) | 2021.06.23 |