[Python3] 프로그래머스 더맵게(heap)

민갱·2023년 7월 11일

CT

목록 보기
27/35

heap 한번 풀어보자.
[Python3] 우선순위 큐 & Heap
[Python3] heapq 사용법

성공.


import heapq

def solution(scoville, K):
    answer = 0
    heapq.heapify(scoville)
    
    while scoville[0] < K:
        if len(scoville) == 1: return -1
        num1,num2 = heapq.heappop(scoville),heapq.heappop(scoville)
        heapq.heappush(scoville,num1 + num2 *2)
        answer+=1        
    return answer

Note

  • heap은 heappop()은 가장 왼쪽 [0]의 위치에 요소를 꺼내고, heappush()는 원하는 요소를 넣고 다시 트리에 맞게 정렬을 해준다(진짜 기특하네🙃)
  • 조건이 모든 요소가 K보다 커야 했기 때문에, 제일 작은 요소 scoville[0]이 K보다 작을떄 까지만(= 모두다 크다는 뜻) 이 조건을 생각 하지 못했다.
profile
가보자고

0개의 댓글