Queue
Task
1. ๊ธฐ๋ฅ๊ฐ๋ฐ in Programmers (Level 2)
https://programmers.co.kr/learn/courses/30/lessons/42586
๐ The point
- Code that is often used when using queue
1 2 3 4
while (!queue.isEmpty()) { int num = queue.poll(); // blah blah blah }
- Convert List
to int[] array - listname.stream().mapToInt(x -> x).toArray();
- Convert List
๐ 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
import java.util.Queue;
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
class Solution {
public int[] solution(int[] progresses, int[] speeds) {
List<Integer> answer = new ArrayList<>();
// 1. make a queue which has the days of each progresses
Queue<Integer> queue = new LinkedList<>();
int n = progresses.length;
for (int i = 0; i < n; i++) {
int day = 0;
while (progresses[i] + speeds[i] * day < 100) day++;
queue.add(day);
}
// 2. find the release day
// case1 : day1 < day2
// case2 : day1 >= day2
int day1 = queue.poll();
int day2 = 0;
int count = 1;
while (!queue.isEmpty()) {
day2 = queue.poll();
if (day1 >= day2) count++;
else {
answer.add(count);
count = 1; // initialization
day1 = day2; // switch
}
}
answer.add(count); // important
return answer.stream().mapToInt(x -> x).toArray();
}
}
// [condition]
// 1. ๋ฐฐํฌ ์ ์์
์ง๋ : progresses (<=100) (value : 1~99)
// 2. ์์
๋ณ '๊ฐ๋ฐ ์๋' : speeds (<=100) (value : 1~100)
// 3. ๋ฐฐํฌ๋ ํ๋ฃจ์ ํ ๋ฒ๋ง, ๋งค์ผ ํ๋ฃจ ๋์
// return ๊ฐ ๋ฐฐํฌ๋ง๋ค ๋ช ๊ฐ์ ๊ธฐ๋ฅ์ด ๋ฐฐํฌ?
// [Logic]
// ๊ฐ์ฅ ์์ ์๋ ๊ธฐ๋ฅ์ด ๊ฐ๋ฐ ์๋ฃ๋ ๋, ์ด๋ฏธ ๊ฐ๋ฐ ์๋ฃ ๋ ๋ค์ ์๋ ๊ธฐ๋ฅ์ด ๊ฐ์ด ๋ฐฐํฌ๋๊ณ out -> ๋ค์ ๊ธฐ๋ฅ๋ค์ด ์ฌ์ ๋ ฌ๋จ -> ๋ฐ๋ณต
// ---> Use LinkedList (Queue : FIFO)
// dynamic programming
// 1. ๋ชจ๋ ๊ธฐ๋ฅ์ด ๊ฐ๋ฐ ์๋ฃ๋๋ ๋ ์ง ๊ตฌํ๊ธฐ
// -> ๊ฐ๋ฐ ์๋ฃ๋๋ ๋ ์ง๋ฅผ linkedlist์ ์ ์ฅํ๊ธฐ ok
// 2. day1 < day2 ๋ผ๋ฉด, answer.add(count), queue์์ poll()
// ์๋๋ผ๋ฉด, (day1 >= day2)
// 3. day1 < day2๊ฐ ๋ ๋๊น์ง count++, queue์์ poll()
// 4. answer.add(count)
// 5. ์๋ก ๋ง๋ค์ด์ง queue๋ก ๋ค์ 1, 2, 3์ ๋ฐ๋ณต
// [Test case]
// 7 3, 9 -> [2, 1]
// 5, 10 1 1, 20 1 -> [1, 3, 2]
// 5, 10 1 1 1, 20 -> [1, 4, 1]
// 5, 10 1 1, 3, 5 -> [1, 3, 1, 1]
/**
System.out.println("day1 : " + day1);
System.out.println("day2 : " + day2);
System.out.println("in loop : " + queue);
System.out.println("count : " + count);
System.out.println("answer : " + answer);
System.out.println();
**/
Important words
- natural number : ์์ฐ์ (1~)
- positive integer : ์์ ์ ์
- negative integer : ์์ ์ ์
Solving problem by using queue is quite fun ๐
Comments powered by Disqus.