[Python] 이중우선큐
1 Try
import heapq
def solution(operations):
answer = [0,0]
stack = []
for o in operations:
try:
line = o.split(' ')
operator, num = line[0], int(line[1])
if operator == 'I': # 해당 값 삽입
stack.append(int(num))
elif int(num) == -1: # 최솟값 삭제
stack.remove(min(stack))
else : # 최댓값 삭제
stack.remove(max(stack))
if(len(stack) == 0):
answer = [0,0]
else :
answer = [max(stack), min(stack)]
except :
continue
return answer
- why? array insert시 int -> string
- 최적화 이슈가 없었기 때문에 통과됨
- 최적화 이슈가 있을 경우 -> heapq 필요할 듯
others
from heapq import heappush, heappop
def solution(arguments):
max_heap = []
min_heap = []
for arg in arguments:
if arg == "D 1":
if max_heap != []:
heappop(max_heap)
if max_heap == [] or -max_heap[0] < min_heap[0]:
min_heap = []
max_heap = []
elif arg == "D -1":
if min_heap != []:
heappop(min_heap)
if min_heap == [] or -max_heap[0] < min_heap[0]:
max_heap = []
min_heap = []
else:
num = int(arg[2:])
heappush(max_heap, -num)
heappush(min_heap, num)
if min_heap == []:
return [0, 0]
return [-heappop(max_heap), heappop(min_heap)]
- heapq 로 min, max heapque 구현할 경우
Author And Source
이 문제에 관하여([Python] 이중우선큐), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kohy0329/Programmers-이중우선큐저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)