프로그래머스_이중우선순위큐_python
2021. 8. 4. 00:04ㆍ코딩테스트
반응형
https://programmers.co.kr/learn/courses/30/lessons/42628
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
def solution(operations):
arr = []
for op in operations:
if op[0] == 'I':
tmp = op[2:]
arr.append(int(tmp))
elif op == 'D 1' and len(arr)>0:
arr.remove(max(arr))
elif op == 'D -1' and len(arr)>0:
arr.remove(min(arr))
if len(arr) > 1:
answer= [max(arr),min(arr)]
else :
answer = [0,0]
return answer
[내코드1]
queue는 사용안함. 리스트와 if,else를 사용해서 해결
import heapq
def solution(operations):
min_h = []
max_h = []
answer = 0
for i in operations:
i = i.split(' ')
i[1] = int(i[1])
if i[0] == 'I':
heapq.heappush(min_h, i[1])
heapq.heappush(max_h, (-i[1], i[1]))
elif i[1] == -1 and len(min_h)>0 :
m = heapq.heappop(min_h)
max_h.remove((-m, m))
elif len(min_h)>0 :
m = heapq.heappop(max_h)
min_h.remove(m[1])
if len(min_h)>0:
return [heapq.heappop(max_h)[1], heapq.heappop(min_h)]
else:
return [0,0]
[내코드2]
heapq의 자동정렬을 사용해서 구현.
반응형
'코딩테스트' 카테고리의 다른 글
프로그래머스_부족한 금액 계산하기_python (0) | 2021.08.04 |
---|---|
프로그래머스_K번째 수_python (0) | 2021.08.04 |
프로그래머스_디스크 컨트롤러_python (0) | 2021.08.01 |
프로그래머스_더 맵게_python (0) | 2021.07.29 |
프로그래머스_다리를 지나는 트럭_python (0) | 2021.07.29 |