이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
| 명령어 | 수신 탑(높이) |
|---|---|
| I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
| D 1 | 큐에서 최댓값을 삭제합니다. |
| D -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
| operations | result |
|---|---|
| ["I 16", "I -5643", "D -1", "D 1", "D 1", "I 123", "D -1"] | [0,0] |
| ["I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"] | [333, -45] |
O(logN)의 시간복잡도를 가지기 때문에 최종적으로 O(N*logN)의 시간복잡도를 가질 것으로 추정했고, 이 때 N은 최대 1,000,000이기 때문에 알맞은 알고리즘으로 보인다.#include <string>
#include <vector>
#include <set>
using namespace std;
vector<int> solution(vector<string> operations) {
vector<int> answer;
multiset<int> mySet;
for(string s : operations){
if(s[0] == 'I'){
mySet.insert(stoi(s.substr(2)));
}else{
if(mySet.empty()) continue;
if(s == "D 1"){
mySet.erase(--mySet.end());
}else{
mySet.erase(mySet.begin());
}
}
}
if(mySet.empty()){
answer = {0, 0};
}else{
answer.push_back(*mySet.rbegin());
answer.push_back(*mySet.begin());
}
return answer;
}