프로그래머스 2023.06.11 (2Lv 프로세스)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제
코딩
#include <string>
#include <vector>
#include <queue>
using namespace std;
struct tNode
{
int iPriorities;
int iLocation;
};
int solution(vector<int> priorities, int location) {
int answer = 0;
int iTarget = 0;
int iNextTarget = 0;
int iCount = 0;
queue<tNode> qwait = {};
for (size_t i = 0; i < priorities.size(); ++i)
{
tNode tempNode = {};
tempNode.iLocation = i;
tempNode.iPriorities = priorities[i];
qwait.push(tempNode);
iTarget = max(iTarget, priorities[i]);
}
while (true)
{
if (qwait.front().iPriorities < iTarget)
{
iNextTarget = max(iNextTarget, qwait.front().iPriorities);
qwait.push(qwait.front());
qwait.pop();
}
else if (qwait.front().iPriorities == iTarget)
{
if (qwait.front().iLocation == location)
{
answer = iCount + 1;
break;
}
else
{
if (iNextTarget == 0)
{
iNextTarget = iTarget;
}
iTarget = iNextTarget;
iNextTarget = 0;
qwait.pop();
iCount++;
}
}
}
return answer;
}
위 코드의 경우 예제로 주어진 입출력에 대해서 결과가 성공하지만, iTarget에 관해 예외 상황이 생긴다. (추후 정리 예정.. 아마?)
때문에 제출 후 채점하기에서는 테스트 실패가 굉장히 많이 나온다.
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct tNode
{
int iPriorities;
int iLocation;
};
int solution(vector<int> priorities, int location) {
int answer = 0;
int iTarget = 0;
int iCount = 0;
queue<tNode> qwait = {};
vector<int> vecsort = {};
for (size_t i = 0; i < priorities.size(); ++i)
{
tNode tempNode = {};
tempNode.iLocation = i;
tempNode.iPriorities = priorities[i];
qwait.push(tempNode);
vecsort.push_back(priorities[i]);
}
sort(vecsort.begin(), vecsort.end(), greater<>());
iTarget = vecsort[0];
vecsort.erase(vecsort.begin());
while (true)
{
if (qwait.front().iPriorities < iTarget)
{
qwait.push(qwait.front());
qwait.pop();
}
else if (qwait.front().iPriorities == iTarget)
{
if (qwait.front().iLocation == location)
{
answer = iCount + 1;
break;
}
else
{
qwait.pop();
iTarget = vecsort[0];
vecsort.erase(vecsort.begin());
iCount++;
}
}
}
return answer;
}
첫 코드에서의 예외 상황 때문에 algorithm 라이브러리 내의 sort() 함수를 이용해 주어진 우선순위 vector(priorities)의 우선순위(int)를 내림차순으로 정렬해, 해당 정렬된 vector(vecsort)의 begin()을 이번 검사의 Target 우선순위로 삼도록 만들었다.
sort() 함수는 기본적으로 오름 차순으로 정렬을 해주고, 3번째 인자로 콜백 함수를 전달해 원하는 정렬 기준을 정해줄 수 있다.
또한, 콜백 함수를 전달할 때, greater<>() 와 less<>()를 이용해 내림, 오름 차순으로 정렬을 할 수 있다.
https://itguava.tistory.com/67
[C++ / STL] sort 함수를 활용한 오름차순 / 내림차순 정렬
blog post Sort 알고리즘 얼마전 현장 코딩 테스트에서 Sort 함수를 활용한 내림차순 정렬을 구현하려고 했는데 키워드가 생각이 안나서 써먹지 못한 경험이 있습니다. 결국은 직접 내림차순 정렬을
itguava.tistory.com
STL 함수를 사용하는 것 보다. 직접 sort 알고리즘을 사용하는 편이 더 좋을 것 같기 때문에, Sort 알고리즘들에 대해 공부를 해야겠다.