이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
16을 삽입 후 최댓값을 삭제합니다. 비어있으므로 [0,0]을 반환합니다.
7,5,-5를 삽입 후 최솟값을 삭제합니다. 최대값 7, 최소값 5를 반환합니다.
import heapq
def solution(operations):
heap = []
max_heap = []
for operation in operations:
operation = operation.split(" ")
if operation[0] == "I":
heapq.heappush(heap,int(operation[1]))
heapq.heappush(max_heap,-int(operation[1]))
else:
if heap:
if operation[1] == "1":
tmp = heapq.heappop(max_heap)
heap.remove(-tmp)
else:
tmp = heapq.heappop(heap)
max_heap.remove(-tmp)
else:
pass
if heap:
return [-heapq.heappop(max_heap),heapq.heappop(heap)]
else:
return [0,0]
힙을 최대 힙, 최소 힙 두 개 만들지 않아도 최소 힙에서 최대값을 삭제할 수 있음
heap = heapq.nlargest(len(heap), heap)[1:]
heapq.heapify(heap)
heapq.nlargest(n, list) 함수를 사용하면 list에서 가장 큰 n개의 수를 뽑아낼 수 있음
import heapq
def solution(operations):
heap = []
for operation in operations:
operation = operation.split(" ")
if operation[0] == "I":
heapq.heappush(heap,int(operation[1]))
else:
if heap:
if operation[1] == "1":
max_ = heapq.nlargest(len(heap), heap)[0]
heap.remove(max_)
else:
heapq.heappop(heap)
else:
pass
if heap:
return [heapq.nlargest(len(heap), heap)[0],heapq.heappop(heap)]
else:
return [0,0]