Algorithm/프로그래머스
[프로그래머스]스택/큐 : 프린터 (level 2) (c++)
HBGB
2020. 4. 28. 22:58
https://programmers.co.kr/learn/courses/30/lessons/42587
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
방법 1: algorithm 라이브러리 사용X
|
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(vector<int> priorities, int location) {
vector<int> order(priorities.size());
queue<int> q;
int ordering = 0;
// 먼저 queue에 모든 인덱스 push
for (int i = 0; i < priorities.size(); i++)
{
q.push(i);
}
while (!q.empty())
{
// 전체에서 우선순위가 가장 높은 값을 가진 인덱스 찾기
// front를 계속해서 queue의 맨 뒤로 보내면서 순회
int now = q.front();
q.push(now);
q.pop();
int max = now;
while (now != q.front())
{
if (priorities[max] < priorities[q.front()])
{
max = q.front();
}
q.push(q.front());
q.pop();
}
// 현재 front에 있는 인덱스 값이 우선순위가 가장 높다면
// order벡터에 출력순서 입력
if (max == now)
{
order[now] = ordering++;
q.pop();
}
// 아니라면 queue의 맨 뒤로
else
{
q.push(now);
q.pop();
}
}
// 원하는 인덱스의 출력순서 return
return order[location] + 1;
}
Colored by Color Scripter
|
방법 2: algorithm 라이브러리 사용O
|
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
32
33
34
35
36
37
38
39
40
41
42
43
|
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int solution(vector<int> priorities, int location) {
vector<int> order(priorities.size());
queue<int> q;
int ordering = 0;
// 먼저 queue에 모든 인덱스 push
for (int i = 0; i < priorities.size(); i++)
{
q.push(i);
}
while (!q.empty())
{
int now = q.front();
// 현재 front 인덱스의 값이 가장 큰 우선순위라면
if (priorities[now] == *max_element(priorities.begin(), priorities.end()))
{
order[now] = ordering++;
q.pop();
// 우선순위에서 해당 인덱스의 우선순위값 -1처리
priorities[now] = -1;
}
// 아니라면 queue의 맨 뒤로
else
{
q.push(now);
q.pop();
}
}
// 원하는 인덱스의 출력순서 return
return order[location] + 1;
}
Colored by Color Scripter
|
방법 1이 방법 2보다 쪼-금 빠르지만
가독성은 역시 방법 2가 더 확실하게 읽힌다.