[Python/Programmers] 이중우선순위큐

문제

1. 난이도: 프로그래머스 Level 3

2. 문제 요약

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

명령어 수신 탑(높이)
I 숫자 : 큐에 주어진 숫자를 삽입합니다.
D 1 : 큐에서 최댓값을 삭제합니다.
D -1 : 큐에서 최솟값을 삭제합니다.
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.

3. 문제 핵심: heap

내 코드

import heapq

def solution(operations):
    heap = []   
    for operation in operations:
        if operation[0] == "I":
            heap.append(int(operation[2:]))
        else:
            if len(heap) <= 0:
                continue
            else:
                if operation[2:] == '-1':
                    print(heap)
                    print("min: ", min(heap))
                    heap.remove(min(heap))
                else:
                    print(heap)
                    print("max: ", max(heap))
                    heap.remove(max(heap))
    if len(heap) >= 2:
        return [max(heap), min(heap)]
    else:
        return [0,0]

다른 코드

ipmort heapq

def solution(operations):
	heap = []
    max_heap = []
    
    for o in operations:
    	current = o.split()
        if current[0] == 'I':
        	hum = int(current[1])
            heapq.heappush(heap, num)
            heapq.heappush(max_heap, (num*-1, num))
        else:
        	lf len(heap) == 0:
            	pass
            elif current[1] == '1'
            	max_value = heapq.heappop(max_heap)[1]
                heap.remove(max_value)
            elif current[1] == '-1':
            	min_value = heapq.heappop(heap)
                max_heap.remove((min_value*-1, min_value))
    if heap:
    	return [heapq.heappop(max_heap[1], heapq.heappop(heap))]
    else:
    	return [0,0]

배운 점

  • heapq.nlargest(n, list)
    -> list에서 가장 큰 n개의 수를 뽑아내는 함수

좋은 웹페이지 즐겨찾기