Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- critical rendering path
- Google Refund
- css framework
- Google Developer API
- java
- --watch
- draganddrop
- SDK upgrade
- OverTheWire
- spread 연산자
- react
- Unity IAP
- MySQL
- Spring Boot
- Camera Zoom
- rpg server
- Digital Ocean
- screencapture
- server
- nodejs
- Packet Network
- Camera Movement
- docker
- unity
- express
- linux
- springboot
- mongoDB
- Unity Editor
- Git
Archives
- Today
- Total
우당탕탕 개발일지
[프로그래머스] Level 3. 이중 우선순위 큐 본문
https://school.programmers.co.kr/learn/courses/30/lessons/42628
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
해결 방법
멀티셋은 자동으로 정렬이 되며, 중복값을 허용하는 자료구조이다. 멀티셋의 맨 앞 요소는 가장 작은 값이, 맨 뒤 요소는 가장 큰 값이들어온다.
#include <string>
#include <vector>
#include <sstream>
#include <set>
using namespace std;
vector<int> solution(vector<string> operations) {
vector<int> answer;
multiset<int> s;
for(int i = 0; i<operations.size(); i++){
istringstream iss(operations[i]);
string command = ""; string numstr ="";
iss>>command >> numstr;
if(command == "I"){
s.insert(stoi(numstr));
}else if(command == "D"){
if(s.size() == 0) continue;
if(numstr == "1") {
auto it = s.end();
--it;
s.erase(it);
}
else s.erase(s.begin());
}
}
if(s.size() ==0) return vector<int>(2,0);;
answer.push_back(*s.rbegin());
answer.push_back(*s.begin());
return answer;
}
다른 풀이
처음엔 최대 우선순위 큐 , 최소 우선순위 큐 2개를 이용하여 풀려고 했었다. 실패했었는데, 여기 그 방법으로 풀어서 성공한 다른 사람의 해결방법이 있다.
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <cstring>
#include <functional>
using namespace std;
priority_queue<int,vector<int>,greater<int>> min_heap;
priority_queue<int> max_heap;
vector<int> solution(vector<string> arguments) {
vector<int> answer;
for(int i=0;i<arguments.size();i++)
{
string a = arguments[i];
char o = a[0];
int n = atoi(a.substr(2).c_str());
if(o == 'I')
{
min_heap.push(n);
max_heap.push(n);
}
else if(o == 'D' && n == 1)
{
if(max_heap.empty()) continue;
if(max_heap.top() == min_heap.top()) min_heap.pop();
max_heap.pop();
}
else if (o == 'D' && n == -1)
{
if(min_heap.empty()) continue;
if(max_heap.top() == min_heap.top()) max_heap.pop();
min_heap.pop();
}
if(max_heap.top() < min_heap.top())
{
while(!min_heap.empty()) min_heap.pop();
while(!max_heap.empty()) max_heap.pop();
}
}
if(min_heap.empty())
{
answer.push_back(0);
answer.push_back(0);
}
else
{
answer.push_back(max_heap.top());
answer.push_back(min_heap.top());
}
return answer;
}
'Algorithm(c++) > Level 3' 카테고리의 다른 글
[프로그래머스] Level 3 . 숫자 게임 (1) | 2025.02.25 |
---|---|
[프로그래머스] Level 3. 최고의 집합 (0) | 2025.02.25 |
[프로그래머스] Level 3. 정수 삼각형 (0) | 2025.02.22 |
[프로그래머스] Level 3. 외벽 점검 (1) | 2025.02.09 |
[프로그래머스] Level 3. 표현 가능한 이진트리 (2) | 2025.02.05 |