프로그래머스_이중우선순위큐_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의 자동정렬을 사용해서 구현.

반응형