(Python) 프로그래머스 - 이중우선순위큐
in Algorithm on Programmers, Level3
[문제 링크]
풀이
import heapq
def solution(operations):
min_q = []
max_q = []
for operation in operations:
oper, num = operation.split()
num = int(num)
if oper == 'I':
heapq.heappush(min_q, num)
heapq.heappush(max_q, -num)
else:
if len(min_q) == 0:
continue
elif num == -1:
heapq.heappop(min_q)
max_q.pop()
elif num == 1:
heapq.heappop(max_q)
min_q.pop()
if len(min_q) == 0:
return [0, 0]
return [-heapq.heappop(max_q), heapq.heappop(min_q)]
우선순위 큐를 두 개 사용하면 된다.
디버그 시켜보면 우선순위 큐에 사용되는 배열에는 최소 힙이면 맨 앞은 최소, 맨뒤는 최대이다. 이걸 이용해서 pop 시키면 된다.