알고리즘/programmers

20210319_코테공부

jungeun960 2021. 3. 19. 21:36

프로그래머스 - 힙(Heap)

# 더 맵게 (Level2)

  • Point. 파이썬 heapq 모듈 사용하기 -> 안하면 효율성 ㄴㄴ
  • 최댓값, 최소값을 뽑을 때는 heap을 사용하라
  • 시도 1) if문 없이 짜면 heap 갯수가 1개 일때 오류가 뜬다
  • 시도 2) if answer == len(scoville)-1 : 로 할 경우 맨 마지막 원소가 K보다 클 경우를 확인하지 못하고 -1 return 
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 : heap_min1 = heapq.heappop(heap)
        if len(heap) >=1 : heap_min2 = heapq.heappop(heap)
        heapq.heappush(heap, heap_min1 + (heap_min2*2))
        answer += 1
        if answer == len(scoville):
            return -1
    
    return answer

 

 

반응형