본문 바로가기
프로그래머스/Lv.2

더 맵게 - Python, heap

by 아찌방 2024. 11. 16.

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/42626

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

 

풀이 - 나의 생각

Heap을 사용하면 쉽게 해결되는 문제였다.

 

주어진 리스트를 힙으로 변환

 

반복문을 돌면서

 

힙의 가장 낮은 값이 K보다 크며 종료

 

작다면

 

두번째 작은 값을 가져와서

 

규칙에 맞게 섞어준다.

 

이걸 반복하면 된다.

 

마지막으로 힙의 최솟값이 K보다 큰지 확인해서

 

성공했는지의 여부를 확인하면 된다.

 

코드

 

import heapq

def solution(scoville, K):
    answer = 0
    heapq.heapify(scoville)

    while len(scoville) > 1:
        first = heapq.heappop(scoville)
        if first >= K: 
            return answer
        second = heapq.heappop(scoville)
        heapq.heappush(scoville, first + second * 2)
        answer += 1

    return answer if scoville[0] >= K else -1

 

 

 

 

 

 

 

다음에 또 봐요

 

728x90