728x90
import heapq
def solution(scoville, K):
answer = 0
heap = [];
for i in scoville :
heapq.heappush(heap, i)
while heap[0] < K :
if len(heap) < 2 :
return -1;
h1 = heapq.heappop(heap);
h2 = heapq.heappop(heap);
mix = h1 + (h2 * 2);
heapq.heappush(heap, mix);
answer+=1;
return answer
풀이 및 회고
파이썬에 heapq 라이브러리를 사용해 간단하게 해결햇습니다.
heaqp 는 '최소힙' 기능을 가지고 있으며 자동으로 정렬을 해줍니다.
heapq 메서드
heappush(heap, item)
해당하는 heap 에 item을 넣는 메서드 입니다.
heappop(heap)
해당하는 heap 에서 가장 작은 (최소) item을 빼는 메서드 입니다.
728x90
'프로그래머스' 카테고리의 다른 글
프로그래머스 LV 2 롤케이크 자르기 (0) | 2024.06.22 |
---|---|
프로그래머스 LV 2 방문길이 (0) | 2024.06.22 |
프로그래머스 LV1 공원산책 (0) | 2024.06.19 |
프로그래머스 LV2 모음사전 (0) | 2024.06.19 |
프로그래머스 LV2 [3차] 압축 (0) | 2024.06.17 |