heapq ๋ชจ๋“ˆ (heapq.heapify(), heapq.heappop(), heapq.heappush())

2020. 10. 30. 17:34ใ†Backend/๐Ÿ Python

heap ๋ชจ๋“ˆ

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ์•ผ๊ทผ์ง€์ˆ˜ ๋ฌธ์ œ๋ฅผ ํ’€๋˜ ์ค‘ ํž™ ์ •๋ ฌ์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ƒ๊ฐํ•˜๊ฒŒ ๋์Šต๋‹ˆ๋‹ค.
heap ๋ชจ๋“ˆ์„ ์šฐ์„  ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.

import heapq

heapify()

์•„๋ž˜๋Š” works๋ผ๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ํž™ ๊ตฌ์กฐ๋กœ ๋ฐ”๊ฟ”์ฃผ๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค. ์ด๋•Œ heapify()๋Š” O(n)๋งŒํผ์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์š”๊ตฌ๋ฉ๋‹ˆ๋‹ค.
ํŒŒ์ด์ฌ์˜ ํž™๊ตฌ์กฐ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ์ตœ์†Œ ํž™ ํ˜•ํƒœ์ž…๋‹ˆ๋‹ค.

works = [3,4,3]
heapq.heapify(works)

์ฃผ์˜ ํ•  ์ ์€, works๋Š” ์ด๋ฏธ ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ์ธ ๊ฐ์ฒด๋ฅผ heap๋ฐฐ์—ด๋กœ ๋ฐ”๊พธ๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์†Œ์š”๋ฉ๋‹ˆ๋‹ค.

์œ„์™€ ๋‹ฌ๋ฆฌ, ๋นˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋Œ€์ƒ์œผ๋กœ ํž™ ๊ตฌ์กฐํ™”๋ฅผ ํ•  ์‹œ์—” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

heapq.heappush() , heapq.heappop()

works2 = []
heapq.heappush(4)

>>> [4]

heapq.heappush(9)

>>> [4, 9]

heapq.heappush(3)

>>> [3, 9, 4]

works2 ๋ฆฌ์ŠคํŠธ๋Š” heappush() ๋ฉ”์†Œ๋“œ๋กœ ์ธํ•ด ํž™๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง€๊ฒŒ ๋์ง€๋งŒ,

heapify()์™€๋Š” ๋‹ฌ๋ฆฌ heappush()์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(log(n))์ด ๋ฉ๋‹ˆ๋‹ค.

์ด๋Š” heappush()์˜ ๋ฐ˜๋Œ€์ธ heappop()๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋™์ผํ•œ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง‘๋‹ˆ๋‹ค.

works = [3, 9, 4]
heapq.heappop(works)

>>> [4, 9]

๊ฒฐ๋ก 

heapq.heapify()์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(n)
heapq.heappush() , heapq.heappop()์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(log(n))