[Programmers]이중우선순위큐(파이썬)

Jihun·2022년 4월 13일
0

Programmers

목록 보기
27/30
post-thumbnail

문제

이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.

이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.

제한 사항

  • operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
  • operations의 원소는 큐가 수행할 연산을 나타냅니다.
    • 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
  • 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.

입출력 예

입출력 예 설명

16을 삽입 후 최댓값을 삭제합니다. 비어있으므로 [0,0]을 반환합니다.
7,5,-5를 삽입 후 최솟값을 삭제합니다. 최대값 7, 최소값 5를 반환합니다.

풀이

  1. 최소 힙과 최대 힙 두 개 만들어서 원소 관리
  2. 한쪽 힙에서 pop이 일어나면 그 원소를 다른 힙에서 삭제해줘서 두 힙을 동기화시켜줌

코드

import heapq
def solution(operations):
    heap = []
    max_heap = []
    for operation in operations:
        operation = operation.split(" ")
        if operation[0] == "I":
            heapq.heappush(heap,int(operation[1]))
            heapq.heappush(max_heap,-int(operation[1]))
        else:
            if heap:
                if operation[1] == "1":
                    tmp = heapq.heappop(max_heap)
                    heap.remove(-tmp)
                else:
                    tmp = heapq.heappop(heap)
                    max_heap.remove(-tmp)
            else:
                pass
    if heap:
        return [-heapq.heappop(max_heap),heapq.heappop(heap)]
    else:
        return [0,0]

+

힙을 최대 힙, 최소 힙 두 개 만들지 않아도 최소 힙에서 최대값을 삭제할 수 있음

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

heapq.nlargest(n, list) 함수를 사용하면 list에서 가장 큰 n개의 수를 뽑아낼 수 있음

heapq.nlargest(n, list)사용 코드

import heapq
def solution(operations):
    heap = []
    for operation in operations:
        operation = operation.split(" ")
        if operation[0] == "I":
            heapq.heappush(heap,int(operation[1]))
        else:
            if heap:
                if operation[1] == "1":
                    max_ = heapq.nlargest(len(heap), heap)[0]
                    heap.remove(max_)
                else:
                    heapq.heappop(heap)
            else:
                pass
    if heap:
        return [heapq.nlargest(len(heap), heap)[0],heapq.heappop(heap)]
    else:
        return [0,0]
profile
slow and steady

0개의 댓글