[프로그래머스] 이중우선순위큐

1 minute read

문제 설명

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

명령어 수신 탑(높이)
I 숫자 큐에 주어진 숫자를 삽입합니다.
D 1 큐에서 최댓값을 삭제합니다.
D -1 큐에서 최솟값을 삭제합니다.

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

제한사항

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

풀이

문제의 이름대로 정직하게 우선순위큐를 2개 선언해서 풀었다. min값과 max값을 위한 두 개의 우선순위 큐를 선언하고, 새로 삽입할 때 마다 두 개의 큐에 모두 삽입해준다. 문제에서는 최댓값과 최솟값만이 필요하므로 굳이 정렬된 상태에서 삭제를 진행할 필요가 없다고 생각했다. 다만 큐가 비어있는 상황에는 우선순위큐를 초기화하여 상태를 맞춰주었다.

코드

#include <string>
#include <vector>
#include <queue>

using namespace std;

vector<int> solution(vector<string> operations) {
    vector<int> answer;
    int qsize = 0;
    priority_queue<int,vector<int>,less<int>> maxheap;
    priority_queue<int,vector<int>,greater<int>> minheap;
    
    for(string op : operations){
        if(qsize == 0){
            while(!maxheap.empty()) maxheap.pop();
            while(!minheap.empty()) minheap.pop();
        }
        
        if(op[0] == 'I'){
            string num = op.substr(2,op.length()-2);
            maxheap.push(stoi(num));
            minheap.push(stoi(num));
            ++qsize;
        }
        else if(op[2] == '1' && qsize > 0){
            maxheap.pop();
            --qsize;
        }
        else if(op[2] == '-' && qsize > 0){
            minheap.pop();
            --qsize;
        }
    }
    
    if(qsize ==0){
        answer.push_back(0);
        answer.push_back(0);
        return answer;
    }
    answer.push_back(maxheap.top());
    answer.push_back(minheap.top());
    return answer;
}

다른 풀이

나는 정직하게(?) 우선순위 큐를 두 개 사용했는데, 내가 푼 방식과 거의 비슷한 방식이지만, set 자료형을 사용하여 더 깔끔하게 풀이한 코드를 발견할 수 있었다.

#include <string>
#include <vector>
#include <set>

using namespace std;

vector<int> solution(vector<string> arguments) {
    vector<int> answer;
    multiset<int> que;
    multiset<int>::iterator iter;
    string sub;

    for(auto s : arguments) {
        sub =s.substr(0, 2);
        if(sub=="I ") que.insert(stoi(s.substr(2,s.length()-2))); 
        else if(s.substr(2,1)=="1"&&que.size()>0) { que.erase(--que.end()); }
        else if(que.size()>0) { que.erase(que.begin()); }
    }

    if(que.size()==0) { answer.push_back(0); answer.push_back(0); }
    else { 
        iter = --que.end(); answer.push_back(*iter); 
        iter = que.begin(); answer.push_back(*iter);
    }

    return answer;
}