코딩테스트
프로그래머스 이중우선순위큐
박준희
2021. 11. 11. 17:19
https://programmers.co.kr/learn/courses/30/lessons/42628
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
import heapq
def solution(operations):
heap = []
for x in operations:
tmp = x.split()
if tmp[0] == "I":
heapq.heappush(heap, int(tmp[1]))
elif tmp[0] == "D" and len(heap) > 0:
if tmp[1] == "1":
del heap[-1]
else:
heapq.heappop(heap)
if len(heap) == 0:
return [0,0]
return [max(heap), heap[0]]
주의
1. 힙은 가장 우선순위가 높은 값이 먼저 pop되는 것을 보장하는 자료구조
그렇기 때문에 최대값을 반환할 때 heap[-1]이 큰 값이라는 보장이 없음
대신 max(heap)를 대신 사용
2. 최대 값을 삭제 할 때 heap[-1]로 삭제하고 있어서 1.의 이유로 통과를 못할 것이라 생각했으나 통과 됌
이유는 잘 모르겠음