문제 설명
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어수신 탑(높이)
I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D 1 | 큐에서 최댓값을 삭제합니다. |
D -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
제한사항
- operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
- operations의 원소는 큐가 수행할 연산을 나타냅니다.
- 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
- 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
입출력 예
operations | return |
[I 16,D 1] | [0,0] |
[I 7,I 5,I -5,D -1] | [7,5] |
풀이
#include <string>
#include <vector>
#include <deque>
#include <algorithm>
#include<iostream>
using namespace std;
vector<int> solution(vector<string> operations) {
vector<int> answer;
deque<int> temp;
for(auto words : operations) {
string num = "";
for(int i=2; i<words.size(); i++) {
num += words[i];
}
if(words[0] == 'I') {
temp.push_back(stoi(num));
sort(temp.begin(), temp.end(), greater<int>());
continue;
}
if(!temp.empty()) {
if(num == "-1")
temp.pop_back();
else
temp.pop_front();
}
}
if(temp.empty()) {
answer.push_back(0);
answer.push_back(0);
}
else {
answer.push_back(temp.front());
answer.push_back(temp.back());
}
return answer;
}
'알고리즘 > 프로그래머스 문제풀이' 카테고리의 다른 글
[프로그래머스] 전화번호 목록 / C++ (0) | 2020.08.29 |
---|---|
[프로그래머스] 완주하지 못한 선수 / C++ (0) | 2020.08.29 |
[프로그래머스] 단어 변환 / C++ (0) | 2020.08.28 |
[프로그래머스] 2 *n 타일링 / C++ (0) | 2020.08.28 |
[프로그래머스] 카카오 프렌즈 컬러링북 / C++ (0) | 2020.08.28 |