🔗링크 https://school.programmers.co.kr/learn/courses/30/lessons/42628
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어 | 수신 | 탑(높이) |
---|---|---|
I | 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D | 1 | 큐에서 최댓값을 삭제합니다. |
D | -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
operations의 원소는 큐가 수행할 연산을 나타냅니다.
원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
힙에 대한 이해도가 높은 상황은 아니다. 최대한 힙을 이용해서 풀어보려 노력했다.
import heapq
def solution(operations):
heap = []
heapq.heapify(heap)
i = 0
while i < len(operations):
fn, num = operations[i].split(' ')
num = int(num)
if fn == 'I' :
heapq.heappush(heap, num)
else:
if len(heap) > 0 :
if num < 1:
heapq.heappop(heap)
else:
heap = heapq.nsmallest(len(heap), heap)
heap.pop()
# print(i,heap)
i+= 1
if len(heap) == 0:
heap = [0]
return [max(heap), min(heap)]
heap
리스트 생성len(operations)
길이만큼 돌릴 준비 operations
에서 fn과 num으로 분리시키기[0,0]
으로 반영해줘야하기 때문에 heap = 0을 넣어줌하지만 이렇게하면 중간데 heap 구조가 깨지는 것으로 확인
그래서 추가 코드를 작성
import heapq
def solution(operations):
heap = []
heapq.heapify(heap)
i = 0
while i < len(operations):
fn, num = operations[i].split(' ')
num = int(num)
if fn == 'I' :
heapq.heappush(heap, num)
else:
if len(heap) > 0 :
if num < 1:
heapq.heappop(heap)
else:
heap = heapq.nsmallest(len(heap), heap)
heap.pop()
heapq.heapify(heap)
# print(i,heap)
i+= 1
if len(heap) == 0:
heap = [0]
return [max(heap), min(heap)]
구조 유지