Today
Total
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
관리 메뉴

기억은 짧고 기록은 길다

[프로그래머스/Programmers] 더 맵게 - Python 본문

CodingTest/programmers

[프로그래머스/Programmers] 더 맵게 - Python

ukunV 2021. 9. 16. 17:44

Link

 

코딩테스트 연습 - 더 맵게

매운 것을 좋아하는 Leo는 모든 음식의 스코빌 지수를 K 이상으로 만들고 싶습니다. 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 Leo는 스코빌 지수가 가장 낮은 두 개의 음식을 아래와 같

programmers.co.kr

 

Solution

해당 문제를 heapq를 사용하지 않고 해결해보려고 했으나 계속 효율성 문제에 걸려 결국 heapq를 사용하였다.

heapq에 대한 자세한 설명은 하단 첨부링크를 확인하기 바란다.

def solution(scoville, K):
    answer = 0

    scoville.sort()

    while True:
        if scoville[0] < K:
            scoville[1] = scoville[0] + scoville[1] * 2
            del scoville[0]
            answer += 1

        scoville.sort()

        t = scoville[0] >= K

        if t == False and len(scoville) == 1:
            return -1
        elif t == True:
            return answer
import heapq

def solution(scoville, K):
    answer = 0

    heapq.heapify(scoville)

    while True:
        if scoville[0] < K:
            t = heapq.heappop(scoville) + heapq.heappop(scoville) * 2
            heapq.heappush(scoville, t)
            answer += 1

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

        if scoville[0] >= K:
            return answer
🔑 key point: heapq

첨부

https://littlefoxdiary.tistory.com/3

Comments