알고리즘 with python/알고리즘 스터디
프로그래머스 이중우선순위큐 python
정민됴
2023. 12. 4. 11:25
heap을 사용해서 푸는 문제였다.
import heapq
def solution(operations):
answer = []
heap = []
for o in operations:
op, num = o.split()
if op == 'I':
heapq.heappush(heap, int(num))
elif op == 'D' and num == '1':
if len(heap) == 0:
continue
heap.remove(max(heap))
elif op == 'D' and num == '-1':
if len(heap) == 0:
continue
heapq.heappop(heap)
if len(heap) == 0:
answer = [0, 0]
else:
answer = [max(heap), heapq.heappop(heap)]
return answer
heap을 사용할 때는 import heap을 사용
heapq.heappush()를 통해 값을 넣고
heapq.heappop()을 하면 기본적으로는 최솟값이 나온다.
최대값을 뺄 때는 그냥 max()를 사용하여 빼주었다.