티스토리 뷰

1. 문제

출처 : 프로그래머스

2. 소스코드

import heapq

def solution(scoville, K):
    answer = 0
    heapq.heapify(scoville) # scoville을 min heap으로 만들기

    while True:
        first = heapq.heappop(scoville) # 가장 작은 원소 pop
        if first >= K: # 가장 작은 원소의 스코빌지수 >= K이면 문제 종료
            #print("answer= ", answer)
            return answer
        if not scoville: # scoville이 비었으면 더 이상 못 함
            return -1  # -1 리턴
        second = heapq.heappop(scoville) # 두번째로 작은 원소 pop

        new = first + 2*second # 섞은 음식 스코빌 = 가장 작은 스코빌 + 2* 두번째로 작은 스코빌
        heapq.heappush(scoville, new) # 섞은 음식 스코빌지수 넣기
        answer += 1 # 섞은 횟수 count
        #print(first, ' + ', second, ' => ', new)
        
    return answer


3. 고찰

1) list에서 원소 제거하기

- index로 제거 : del ListName[index]

- index pop : ListName.pop(index)

- key값으로 제거하기 : ListName.remove(key)

- list원소 모두 제거하기 : ListName.clear()

 

2) heapq모듈

- 최소 힙으로 바꾸기: heapq.heapify(ListName)

- 최대 힙으로 바꾸기: heapq._heapify_max(ListName)

- 힙에 원소 추가 : heapq.heappush(HeapName, item)

- 힙에 원소 삭제 : heapq.heappop(HeapName)

- 최소값/최대값 얻기 : HeapName[0]

    인덱스0에는 항상 가장 작은 값/가장 큰 값이 위치하지만, heap 자료구조는 반정렬상태이기 때문에 그 다음 인덱스에는 두번째 작은/큰 원소라는 보장이 없다.

 

'프로그래밍 > Python' 카테고리의 다른 글

프로그래머스_구명보트  (0) 2020.10.29
프로그래머스_기능개발  (0) 2020.10.04
프로그래머스_프린터  (0) 2020.10.01
프로그래머스_다리를 건너는 트럭  (0) 2020.09.28
프로그래머스_주식가격  (0) 2020.09.28
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/02   »
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
글 보관함