Link: https://programmers.co.kr/learn/courses/30/lessons/42628?language=python3
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어 수신 탑(높이)
I 숫자 큐에 주어진 숫자를 삽입합니다.
D 1 큐에서 최댓값을 삭제합니다.
D -1 큐에서 최솟값을 삭제합니다.
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
operations return
["I 16","D 1"][0,0]
["I 7","I 5","I -5","D -1"][7,5]
16을 삽입 후 최댓값을 삭제합니다. 비어있으므로 [0,0]을 반환합니다.
7,5,-5를 삽입 후 최솟값을 삭제합니다. 최대값 7, 최소값 5를 반환합니다.
import heapq
def solution(operations):
answer = []
heap = []
for x in operations:
op = x.split()[0]
num = int(x.split()[1])
if op == "I":
heapq.heappush(heap,num)
else:
if not heap: continue
if num == -1:
heapq.heapify(heap)
heapq.heappop(heap)
else:
heapq._heapify_max(heap)
heapq._heappop_max(heap)
if not heap:
return [0,0]
else:
heapq._heapify_max(heap)
answer.append(heap[0])
heapq.heapify(heap)
answer.append(heap[0])
return answer
#1
Input: solution(["I 16","D 1"])
Output: [0,0]
#2
Input: solution(["I 7","I 5","I -5","D -1"])
Output: [7,5]