ํ’€์ด

๊ฐ€์žฅ ์ตœ์†Œ์ธ ๋…€์„์„ ๊ณ„์†ํ•ด์„œ ๋ฝ‘์•„์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— 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
 

Reference