ํ์ด
๊ฐ์ฅ ์ต์์ธ ๋ ์์ ๊ณ์ํด์ ๋ฝ์์ผ ํ๊ธฐ ๋๋ฌธ์ heap ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ค. ์ด ๋ python์ผ๋ก ์ฝ๋ฉ์ ํ๋ คํ๋ค๋ฉด ๋ฌด์กฐ๊ฑด์ ์ผ๋ก heapq๋ฅผ ์ฌ์ฉํ ๊ฒ. priorityQueue๋ ์๋๊ฐ ๋๋ฌด ๋๋ ค์ ํจ์จ์ฑ ํต๊ณผ๋ฅผ ํ์ง ๋ชปํ๋ค.
Code
import heapq
def solution(scoville, K):
# ๊ฐ์ฅ ์์ ์์๋ฅผ ๊ฐ์ ธ์จ๋ค
# ๊ทธ ๋
์์ด K๋ณด๋ค ํฐ์ง ํ์
ํ๋ค.
# ์๋๋ฉด
# ๊ทธ ๋ค์ ์์๋ฅผ ๊ฐ์ ธ์จ๋ค
# ์๋๋ค.
# ์์ ํ์ 1์ถ๊ฐํ๋ค.
# ๋ค์ ๋ฃ๋๋ค.
# ๋ฐ๋ณตํ๋ค.
q = scoville[:]
heapq.heapify(q)
count = 0
while q[0] < K and len(q) > 1: # ์ ์ผ ์์ ์์๊ฐ K๋ณด๋ค ์๊ณ ๋ค์ด๊ฐ ๊ฐ์๋ 2์ด์์ด๋ฉด ์งํ
a = heapq.heappop(q)
b = heapq.heappop(q)
c = a + b * 2
heapq.heappush(q, c)
count += 1
if q[0] >= K:
return count
else:
return -1