문제풀이/Programmers
[Python] 프로그래머스 - 이중우선순위큐
hbj0209
2021. 5. 8. 14:14
728x90
반응형
programmers.co.kr/learn/courses/30/lessons/42628
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
기본 heapq문제이다. 파이썬에서 '우선순위큐'를 사용하려면 priorityQueue가 아닌 heapq를 사용해야한다.
import heapq
def solution(operations):
# 힙 정렬
def heap_sort(nums):
heap = []
for num in nums:
heapq.heappush(heap, num)
sorted_nums = []
while heap:
sorted_nums.append(heapq.heappop(heap))
return sorted_nums
h = []
for o in operations:
op = o.split()
# 명령어가 I이면 h 힙에 숫자 삽입
if op[0] == 'I':
heapq.heappush(h, int(op[1]))
# 명령어가 D 1 이면 힙정렬을 한 뒤 마지막 원소가 최댓값이므로 pop(-1)
elif op[0] == 'D' and op[1] == '1':
if h:
h = heap_sort(h)
h.pop(-1)
# 명령어가 D -1 이면 그냥 heap의 첫번째 원소 pop
else:
if h:
heapq.heappop(h)
# h가 비어있으면 [0, 0] 아니면 [최댓값, 최솟값] 출력
return [max(h), min(h)] if h else [0,0]
(프로그래머스 level: 3)
728x90
반응형