[프그] 힙 : 더 맵게

yozzum·2022년 7월 17일
0

https://school.programmers.co.kr/learn/courses/30/lessons/42626/solution_groups?language=python3&type=my

아이디어

  • 직관적인 로직이다.
  • 단순히 스택을 활용해서도 풀 수 있지만, loop 마다 정렬을 해줘야하기에 효율성 체크에 걸린다.
  • 힙을 이용해서 풀면 된다.

코드(성공)

import heapq

def solution(scoville, K):

    heapq.heapify(scoville) # heap 자료구조
    cnt = 0

    while True:
        if len(scoville) == 1 and scoville[0] < K:
            return -1

        a = heapq.heappop(scoville)
        if a < K:
            b = heapq.heappop(scoville)
            new = a + (b * 2)
            heapq.heappush(scoville, new)
            cnt += 1    
        else:
            return cnt
profile
yozzum

0개의 댓글