Queue
Task
2. ํ๋ฆฐํฐ in Programmers (Level 2)
https://programmers.co.kr/learn/courses/30/lessons/42587
๐ The point
- Code that is often used when using queue
1 2 3 4
while (!queue.isEmpty()) { int num = queue.poll(); // blah blah blah }
- Used custom class
- Input class to queue
- Used boolean flag
๐ Answer
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.Queue;
import java.util.LinkedList;
class Solution {
class Task {
int index;
int priority;
public Task(int index, int priority) {
this.index = index;
this.priority = priority;
}
}
public int solution(int[] priorities, int location) {
int answer = 0;
// make queue of printing
Queue<Task> queue = new LinkedList<>();
for (int i = 0; i < priorities.length; i++) {
queue.add(new Task(i, priorities[i]));
}
int nowIndex = 0;
while (!queue.isEmpty()) {
// get first task
Task currTask = queue.poll();
boolean flag = false;
// true if there are bigger priorities in remaining queue
for (Task t : queue)
if (t.priority > currTask.priority) flag = true;
if (flag) queue.add(currTask);
else { // if it's the biggest priority
// to skip big priority in order from next time
nowIndex++;
// if it's my print
if (currTask.index == location) {
answer = nowIndex;
break;
}
}
}
return answer;
}
}
/**
์ค์๋๊ฐ ๋์ ๋ฌธ์๋ฅผ ๋จผ์ ์ธ์ํ๋ ํ๋ฆฐํฐ
[Logic]
1. ์ธ์ ๋๊ธฐ๋ชฉ๋ก์ ๊ฐ์ฅ ์์ ์๋ ๋ฌธ์(J)๋ฅผ ๋๊ธฐ๋ชฉ๋ก์์ ๊บผ๋
๋๋ค.
2. ๋๋จธ์ง ์ธ์ ๋๊ธฐ๋ชฉ๋ก์์ J๋ณด๋ค ์ค์๋๊ฐ ๋์ ๋ฌธ์๊ฐ ํ ๊ฐ๋ผ๋ ์กด์ฌํ๋ฉด, J๋ฅผ ๋๊ธฐ๋ชฉ๋ก์ ๊ฐ์ฅ ๋ง์ง๋ง์ ๋ฃ์ต๋๋ค.
3. ๊ทธ๋ ์ง ์์ผ๋ฉด J๋ฅผ ์ธ์ํฉ๋๋ค.
return ๋ด๊ฐ ์ธ์๋ฅผ ์์ฒญํ ๋ฌธ์๊ฐ ๋ช ๋ฒ์งธ๋ก ์ธ์๋๋์ง
[Condition]
- priorities : ๋ฌธ์์ ์ค์๋ ๋ฐฐ์ด (value : 1~9)
- location : ๋ด๊ฐ ์ธ์๋ฅผ ์์ฒญํ ๋ฌธ์๊ฐ ํ์ฌ ๋๊ธฐ๋ชฉ๋ก์ ์ด๋ค ์์น์ ์๋์ง (0~99 like index of array)
** the number of documents : 1 ~ 100
- ex. priorities : 1 1 9 1 1 1 -> print by order 'C D E F A B'
**/
// [Test case]
// 2 1 3 2 -> 1 3 2 2 -> 3 2 2 1 -> return 1
// 9 1 1 1 1 1 -> return 5
// 3 5 1 2 4 2, 4(4)
My head canโt work well anymoreโฆ. Iโm gonna go back home
Comments powered by Disqus.