티스토리 뷰

반응형

문제

 

코딩테스트 연습 - 더 맵게

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

programmers.co.kr

 

나의 풀이

def solution(scoville, K):
    count = 0
    short = []

    for each in scoville:
        if each < K:
            short.append(each)

    short.sort()

    while True:
        if len(short) == 0:
            return -1
        count += 1
        if len(short) == 1:
            break
        else:
            addition = short[0] + short[1]
            short.pop()
            short.pop()
            if addition < K:
                insertsort_right(short, addition)

    return count

def insertsort_right(arr, a):
    for i in range(len(arr)):
        if arr[len(arr) - 1 - i] >= a:
            arr.insert(i, a)
            break

 

 

이렇게 편한게 있는지 몰랐다

heapify를 사용하면 자동으로 minheap구조로 바꿔준다

import heapq

def solution(scoville, K):
    #  scoville을 minheap구조로 바꿈
    heapq.heapify(scoville)
    count = 0

    while len(scoville) > 1:
        count += 1
        
        f = heapq.heappop(scoville)
        s = heapq.heappop(scoville)
        
        heapq.heappush(scoville, f+s*2)
        if scoville[0] >= K:
            return count

    return -1
반응형