Coding - Algo/python

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

jainn 2021. 6. 20. 01:05
728x90

문제

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

 

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

 

programmers.co.kr

 

풀이 및 소스코드

heapq.nlargest(n , hq)

위 nlargest함수는 hq 라는 이름을 가진 힙큐에서의 최댓값을 n개 만큼 출력하는 함수이다.

hq = heapq.nlargest(len(hq), hq)[1:]
heapq.heapify(hq)

따라서 nlargest 함수로 hq의 길이만큼 최대값을 출력할 때 0번째 원소를 빼고 나머지 결과값을 다시 hq에 넣는다면 최대값을 뺀 힙큐를 구현할 수 있다.

import heapq
def solution(operations):
    hq = []
    for oper in operations:
        num = int(oper[2:])
        if oper[0] =='I':
            heapq.heappush(hq, num)
        else:
            if len(hq) == 0:
                continue
            elif num == 1:
                hq = heapq.nlargest(len(hq), hq)[1:]
                heapq.heapify(hq)
            else:
                print(heapq.heappop(hq))
        print(hq)
    if len(hq)==0:
        return [0, 0]
    else:
        return [heapq.nlargest(1, hq)[0], heapq.nsmallest(1, hq)[0]]
반응형