동캄의 코딩도장

프로그래머스 level3 [이중우선순위큐] 파이썬 본문

코테/프로그래머스

프로그래머스 level3 [이중우선순위큐] 파이썬

동 캄 2022. 4. 7. 21:18

https://programmers.co.kr/learn/courses/30/lessons/42628

 

코딩테스트 연습 - 이중우선순위큐

 

programmers.co.kr

# 프로그래머스 이중우선순위큐

import heapq


def solution(operations):
    answer = []
    heap = []
    for operation in operations:
        oper, digit = map(str, operation.split())
        if oper == 'I':
            heapq.heappush(heap, int(digit))
        elif heap and oper == 'D' and digit == '1':
            heap = heapq.nlargest(len(heap), heap)[1:]
            heapq.heapify(heap)
        elif heap and oper == 'D' and digit == '-1':
            heapq.heappop(heap)
    if heap:
        M = heapq.nlargest(len(heap), heap)[0]
        heapq.heapify(heap)
        answer.append(M)
        answer.append(heap[0])
    else:
        answer.append(0)
        answer.append(0)
    return answer

heapq 라이브러리를 이용하여 문제를 간단히 해결할 수 있었다.

 

(이번 문제를 통해 heapq의 nlargest 함수의 사용법에 대해 알게 되었다. 기억해두자!)