본문 바로가기

c++/프로그래머스

프로그래머스 : 이중우선순위 큐 C++

programmers.co.kr/learn/courses/30/lessons/42628

 

코딩테스트 연습 - 이중우선순위큐

 

programmers.co.kr

 

풀이 및 후기

1. 처음에 걍 벡터로 하면된다는 생각이 안떠올라서 우선순위 큐 써서 막 하고 그랬는데 걍 이 방법이 짱이다~

2. 삽입할때 마다 벡터를 sort해버리면 됨!!

 

#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

vector<int> solution(vector<string> operations) {
    vector<int> answer;
    string data;
    int value;
    vector<int> end;
    for(int i=0;i<operations.size();i++)
    {
        if(operations[i][0]=='I')
        {
            data = operations[i].substr(operations[i].find("I")+2, operations[i].npos);
            value = stoi(data);
            end.push_back(value);
            sort(end.begin(),end.end());//오름 차순
        }
        else if(operations[i]=="D -1")
        {
            if(!end.empty())// 빈큐에 데이터 삭제하라는 명령오면 무시
                end.erase(end.begin());
        }
        else if(operations[i]=="D 1")
        {
            if(!end.empty())
                end.pop_back();
        }
    }
    
    //최댓값, 최솟값 순
    if(!end.empty())
    {
        answer.push_back(end[end.size()-1]);
        answer.push_back(end[0]);
    }
    else
    {
        answer.push_back(0);
        answer.push_back(0);
    }
    
    return answer;
}