programmers - 힙 - 이중우선순위 큐

marafo·2020년 8월 30일
post-thumbnail

문제 설명

이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.

이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.

제한사항

1) operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
2) operations의 원소는 큐가 수행할 연산을 나타냅니다.
3) 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
4) 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.

입출력 예 설명

16을 삽입 후 최댓값을 삭제합니다. 비어있으므로 [0,0]을 반환합니다.
7,5,-5를 삽입 후 최솟값을 삭제합니다. 최대값 7, 최소값 5를 반환합니다.


function solution(operations) {
    let answer;
    let queue = [];
    let i = 0;
    
    while( i < operations.length ){
        if(operations[i][0] === 'I'){
            queue.push( Number( operations[i].slice(2) ));
        }else if( operations[i][0] === 'D'){
            if( operations[i][2] === '1' ){
                queue.splice( queue.indexOf( Math.max(...queue) ), 1);
            }else{
                queue.splice( queue.indexOf( Math.min(...queue) ), 1);
            }
        }
        if( i === operations.length - 1 && queue.length !==0 ){
            return [Math.max(...queue), Math.min(...queue)];
            break;
        }
        i++;
    }
    
    return [0, 0];
}

문자열, 배열, 숫자형을 변환할 때 약간 버벅였지만 전체적으로 수월하게 풀었다. 우선순위 큐의 기본을 충실히 묻는 문제.

while문의 마지막 if절에서 queue의 길이가 0이 아닐 때로 해주어야 빈 배열일 경우 마지막 줄에 [0,0]을 반환할 수 있도록 넘어간다.


+) python version

def solution(operations):
    li = []
    queue = []
    
    for i in range(len(operations)):
        if operations[i][0] == 'I':
            queue.append(int(operations[i][2:]))
            queue.sort()
        if operations[i][0] == 'D':
            if operations[i][2] == '1' and len(queue):
                queue.pop()
            elif operations[i][2] == '-' and len(queue):
                queue.pop(0)

    if len(queue):
        return [max(queue), min(queue)]
    else:
        return [0, 0]
    

일반 배열에서 pop(0) => 큐에서 popleft() 기능

profile
프론트 개발자 준비

0개의 댓글