이중우선순위큐(python)

이민호·2021년 3월 20일
0

나의 문제풀이

  1. 요소를 받아오기
    operations의 요소(i_split)를 받아서 리스트 heap과 max_heap에 heappop()을 이용하여 i_split[1]을넣어준다.
  • 이때 max_heap에는 내림차순으로 넣어주기 위하여 (-i_split[1], i_split[1]) 형식으로 넣어준다.
  1. D 1일때
    max_heap[0]을 heappop()으로 빼주고, 이 값을 리스트 heap에서도 빼준다.

  2. D 2일때
    heap[0]을 heappop()으로 빼주고, 이값을 max_heap에서도 빼준다.

import heapq
def solution(operations):
    answer = []
    heap = []
    max_heap = []
    .
    # operations의 요소(i_split)들을 받아온다.
    for i in operations:
        i_split = i.split(" ")
        if i_split[0] == "I":
            heapq.heappush(heap,int(i_split[1]))
            heapq.heappush(max_heap,[(int(i_split[1])*-1), int(i_split[1])])
        else:
            if len(heap) == 0:
                pass
            elif i_split[1] == '1':
                num = heapq.heappop(max_heap)[1]
                heap.remove(num)
            else:
                num = heapq.heappop(heap)
                max_heap.remove([(num*-1), num])
.
    if len(heap) == 0:
        answer = [0,0]
    else:
        answer = [max(heap), min(heap)]
.    
    return answer

다른사람의 풀이

heap의 최대값을 제거하는 방법을 heapq.nlargest()를 이용하여 간편하게 실행 할 수 있다.

heap = heapq.nlargest(len(heap), heap)[1:]
heapq.heapify(heap)
profile
life is fun

0개의 댓글

관련 채용 정보