나의 풀이
import heapq
def solution(scoville, K):
cnt=0
heap=[]
for x in scoville:
heapq.heappush(heap, x)
if heap[0]>=K:
return cnt
while(len(heap)>1):
첫번째로 가장 작은 원소를 pop한다.
min1=heapq.heappop(heap)
또 남아있는 것 중에서 가장 작은 원소를 pop한다.
min2=heapq.heappop(heap)
new_scoville=min1+(min2*2)
heap.append(new_scoville)
cnt+=1
if heap[0]>=K:
return cnt
return -1
힙(자료구조)의 활용
▶ import heapq
heap =[]
heapq.heappush(heap, item) : item을 heap에 추가
heapq.heappop(heap) : heap에서 가장 작은 원소를 pop & 리턴. 비어 있는 경우 IndexError가 호출됨.
heapq.heapify(x) : 리스트 x를 즉각적으로 heap으로 변환함 (in linear time, O(N) )
'프로그래머스(파이썬) > LV.2(파이썬)' 카테고리의 다른 글
[3차] 압축 → 전진 + 후진, 슬라이싱 "첫자리" 갱신 (0) | 2023.01.03 |
---|---|
H-index → 논문을 적게 발표했지만, 인용된 수가 많은 good 케이스 (0) | 2023.01.03 |
귤 고르기→ Counter() 함수, most_common() (0) | 2023.01.02 |
k진수에서 소수 개수 구하기→ 10진수를 n진법, 소수 판별★,filter()함수★ (0) | 2023.01.02 |
타켓넘버→ DFS(깊이우선탐색)★★+요소 더하기, 요소 빼기+ 재귀함수 (0) | 2022.12.30 |