https://programmers.co.kr/learn/courses/30/lessons/42587
옛날에 풀어놨었나 본데.. 아래에서 개선해보자.
int solution(vector<int> priorities, int location) {
vector <pair< int, int >> result(priorities.size());
vector <pair< int, int >>::iterator it;
vector<pair<int, int>> temp;
int resultSize = result.size();
int index = 0;
int answer = 0;
bool isChage = false;
for (it = result.begin(); it != result.end(); it++)
{
it->first = index;
it->second = priorities[index];
index++;
}
for (int i = 0; i < resultSize; i++)
{
for (int j = i + 1; j < result.size(); j++)
{
if (result[i].second < result[j].second)
{
isChage = true;
int tempF = result[0].first;
int tempS = result[0].second;
result.erase(result.begin());
result.push_back(make_pair(tempF, tempS));
break;
}
else
isChage = false;
}
if (isChage == true)
i = -1;
else
{
temp.push_back(make_pair(result[0].first, result[0].second));
result.erase(result.begin());
i = -1;
}
if (result.size() == 0)
break;
}
index = 0;
for (it = temp.begin(); it != temp.end(); it++)
{
if (it->first == location)
{
answer = index + 1;
break;
}
index++;
}
return answer;
}
queue를 이용하자. 좀 더 짧아지긴 했네..
int solution(vector<int> priorities, int location) {
int answer = 0;
queue<pair<int, int>> q; // 우선순위와 몇 번째 idx 값이었는지 저장
priority_queue<int> pq; // priority 값 저장
int max = -2147000000;
for (int i = 0; i < priorities.size(); i++) {
q.push({ priorities[i], i });
pq.push(priorities[i]);
}
while (!q.empty()) {
if (q.front().first < pq.top()) {
auto pri = q.front();
q.pop();
q.push(pri);
}
else {
if (q.front().second == location) {
answer++;
break;
}
q.pop();
pq.pop();
answer++;
}
}
return answer;
}