이중 우선순위 큐는 입력된 명령어에 다음 연산을 하는 자료구조 입니다.
명령어 | 수신 탑(높이) |
---|---|
I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D 1 | 큐에서 최댓값을 삭제합니다. |
I 숫자 | 큐에서 최솟값을 삭제합니다. |
모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
operations | return |
---|---|
[I 16,D 1] | [0,0] |
[I 7,I 5,I -5,D -1] | [7,5] |
import heapq
def solution(operations) :
count =0
stack_result = []
heap_min_result, heap_max_result= [], []
for operation in operations : # 명령어는 앞에 위치하기 때문
oper_command, oper_number = operation.split()
if oper_command == 'I' : # heap push 작업
count +=1
stack_result.append(int(oper_number))
elif oper_command == 'D' : # 삭제 작업
if count == 0 : # 비어있는 큐일때
continue
count-=1
if oper_number == '-1' : # 최소값 삭제
heap_min_result = stack_result[:]
heapq.heapify(heap_min_result)
stack_result.remove((heapq.heappop(heap_min_result) ) )
else : # 최대 값 삭제
heap_max_result =list(map( lambda x:-x , stack_result[:] ))
heapq.heapify(heap_max_result)
stack_result.remove(-(heapq.heappop(heap_max_result) ) )
heap_min_result,heap_max_result = stack_result[:] ,list(map( lambda x:-x , stack_result[:] ))
heapq.heapify(heap_min_result)
heapq.heapify(heap_max_result)
if count ==0 : # 힙이 비어져 있는 경우
return [0,0]
else :
return [-(heap_max_result[0]) , heap_min_result[0] ]
최대힙과 최소힙을 구현할 리스트(heap_min_result, heap_max_result)를 생성한 후 명령어가 문자열이므로 split()해서 숫자 부분과 영어 부분을 구분한다.
ex) "D 5" => oper_command =D , oper_number = 5
최대힙과 최소힙의 내용을 동기화 해주기 위해서 또다른 리스트를 하나 생성한 후 명령어를 할 때마다 초기화를 해주어서 최대힙과 최소힙의 내용을 동기화 시켜준다.
여기서 최소힙 같은 경우 값을 넣을때 별다른 작업을 안해도 되지만 최대힙은 "추가"에서 적은 원리를 적용해서 map 함수에서 lambda 함수를 사용해 heapq에 들어가는 값에 -를 붙여서 최대힙을 구현해주면 된다.