코딩테스트 연습 > 힙(Heap) > 더 맵게

파이톨치·2022년 2월 5일
2
post-thumbnail

문제

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

코드

1차 시도

def solution(scoville, K):
    answer = 0
    scovile = sorted(scoville)
    
    l = 0

    while scoville[0] < K:
        scoville[0] = scoville[0] + scoville[1] * 2
        scoville.pop(1)
        scoville.sort()  
        #print(scoville)
        answer += 1
        l += 1
        
        if l >= len(scoville):
            return -1
    return answer

아! 이거 힙 쓰는 문제였지!!

2차 시도

import heapq

def solution(scoville, K):
    answer = 0
    heap = []

    for item in scoville:
        heapq.heappush(heap, item)
        
    #print(heap)
    
    while heap[0] < K:
        heapq.heappush(heap, heapq.heappop(heap) + heapq.heappop(heap) * 2)
        answer += 1
    return answer

거의 다 됐다

3차 시도

import heapq

def solution(scoville, K):
    answer = 0
    heap = []

    for item in scoville:
        heapq.heappush(heap, item)
        
    while heap[0] < K:
        try:
            heapq.heappush(heap, heapq.heappop(heap) + heapq.heappop(heap) * 2)
        except:
            return -1
        answer += 1
    return answer


나이스!

profile
안알랴줌

0개의 댓글