프로그래머스 알고리즘: 이중우선순위큐 (lv3)

sen·2022년 9월 20일
0

https://school.programmers.co.kr/learn/courses/30/lessons/42628?language=python3


from heapq import heappop, heappush

def solution(operations):
    answer = []
    max_list = []
    min_list = []
    del_list = {}
    cnt_insert = 0
    cnt_delete = 0
    
    for op in operations:
        try:
            if op[0] == 'I':
                op = op.split()
                heappush(max_list, -int(op[1]))
                heappush(min_list, int(op[1]))
                cnt_insert += 1
            elif op == 'D -1':
                while min_list[0] in del_list:
                    heappop(min_list)
                del_list[heappop(min_list)] = 0
                cnt_delete += 1
            elif op == 'D 1':
                while -max_list[0] in del_list:
                    heappop(max_list)
                del_list[-heappop(max_list)] = 0
                cnt_delete += 1
        except:
            pass
    
    if cnt_delete == cnt_insert:
        return [0, 0]
    
    try:
        while -max_list[0] in del_list:
            heappop(max_list)
        while min_list[0] in del_list:
            heappop(min_list)
    except:
        pass
    
    max_val = -max_list[0] if max_list else min_list[0]
    min_val = min_list[0] if min_list else -max_list[0]
    return [max_val, min_val]

  • 처음에 내림차순, 오름차순 heap을 따로 만들어 각각 마지막으로 삭제한 값을 저장하는 방식으로 구현했으나 한 개의 테케 실패
    -> 나중에 insert 하는 값이 있을 경우 순서가 꼬이게 됨
  • 다른 사람의 코드를 참고해 삭제된 값들을 저장하는 dict을 만들어 빠르게 해당 값의 삭제유무를 탐색함
  • 어이없던 점: heap은 맨 앞 원소의 최솟값을 보장하지만 전체 리스트의 정렬을 보장하지 않는데 현재 테케들론 맨 뒷 원소를 최댓값이라고 가정하고 구현해도 통과 되는 코드가 있었음
profile
𝙝𝙞 𝙩𝙝𝙚𝙧𝙚 😎

0개의 댓글