Problem Solving/Programmers
프로그래머스 (Level 3) : 이중우선순위큐 / Python, heapq, try-except
eroke
2022. 5. 5. 23:43
프로그래머스 '더맵게' 로 힙을 접한 뒤 복습할 겸 힙문제를 풀어봤다.
> 더맵게 문제 풀이 (https://rokroks.tistory.com/111)
문제
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
문자열로 들어오는 명령어로 값을 push하거나 최대/최소값을 pop 한뒤
최종적으로 [최댓값,최솟값]을 return하는 문제이다.
파이썬 heapq는 기본적으로 최소힙인데 해당 문제는 최대힙도 이용해야한다.
파이썬에서 최대힙을 이용하는 방법은 push/pop 시에 데이터를 음수로 넣는 것이다.
풀이
import heapq as h
def solution(operations):
answer = []
h1=[] #최소힙
h2=[] #최대힙
h3=[] #빈큐 확인용 힙
for s in operations:
o,n=s.split()
n=int(n)
if o=='I':
h.heappush(h1,n) #최소힙
h.heappush(h2,-n) #최대힙
h.heappush(h3,n)
elif o=='D':
try:
if n==1:
h.heappop(h2)
h.heappop(h3)
elif n==-1:
h.heappop(h1)
h.heappop(h3)
if len(h3)==0: #초기화
h1=[]
h2=[]
except IndexError: continue
if len(h3)==0:
answer=[0,0]
else:
answer.append(-h2[0]) #최대값
answer.append(h1[0]) #최소값
return answer
최소힙, 최대힙, 빈큐 확인용 힙 총 3개의 힙으로 풀었다..
반응형