[Python] 힙_이중우선순위큐[3단계]

EunBi Na·2022년 4월 19일
0

문제 설명

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

명령어수신 탑(높이)
I 숫자큐에 주어진 숫자를 삽입합니다.
D 1큐에서 최댓값을 삭제합니다.
D -1큐에서 최솟값을 삭제합니다.

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

제한사항

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

입출력 예

operationsreturn
["I 16","D 1"][0,0]
["I 7","I 5","I -5","D -1"][7,5]

입출력 예 설명

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

자바 풀이

import heapq

def solution(operations):
    answer = []
    heap = []   # 힙 생성

    for data in operations:
        # 연산이 "I"일 경우 공백 뒤의 숫자를 heap에 넣음
        if data[0] == "I":
            heapq.heappush(heap, int(data[2:]))
        # 연산이 "D"일 경우
        else:
            if len(heap) == 0:
                pass
            # 공백 뒤가 "-"일 경우 최소힙을 제거
            elif data[2] == "-":
                heapq.heappop(heap)
            # 공백 뒤가 아무것도 아닌 경우
            else:
                # 힙에서 가장 큰 수를 제외하고 다시 힙에 넣음
                heap = heapq.nlargest(len(heap), heap)[1:]
                heapq.heapify(heap)

    if heap:
        answer.append(max(heap))
        answer.append(min(heap))
    else:
        answer.append(0)
        answer.append(0)
    
    return answer
import heapq

def solution(operations):
    min_heap = []
    for value in operations:
        order, data = value.split()
        data = int(data)
        # 최댓값 삭제
        if order == "D" and data == 1:
            if min_heap:
                max_value = max(min_heap)
                min_heap.remove(max_value)
        # 최솟값 삭제
        elif order == "D" and data == -1:
            if min_heap:
                heapq.heappop(min_heap)
        # 큐 데이터 삽입
        else:
            heapq.heappush(min_heap, data)
    
    # heap이 비어있는 경우
    if not min_heap:
        return [0, 0]
    return max(min_heap), min_heap[0]
profile
This is a velog that freely records the process I learn.

0개의 댓글