Queue
Task
Previous task 1 Previous task 2
๐ 3. ๋ค๋ฆฌ๋ฅผ ์ง๋๋ ํธ๋ญ in Programmers (Level 2)
โญ๏ธ The point
- Used while loop and break
๐ 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
import java.util.Queue;
import java.util.LinkedList;
class Solution {
private Queue<Integer> queue;
public int solution(int bridge_length, int weight, int[] truck_weights) {
int time = 0;
int sumOfWeight = 0;
queue = new LinkedList<>();
for (int i = 0; i < truck_weights.length; i++) {
int truck = truck_weights[i];
while (true) {
// case1. just add truck, don't need to consider sum of weights
if (queue.isEmpty()) {
queue.add(truck);
sumOfWeight += truck;
time++;
break; // already added truck, so go out whlie loop
}
// case2. add truck and need to consider sum of weights
else if (!queue.isEmpty() && queue.size() == bridge_length) {
int arrived = queue.poll();
sumOfWeight -= arrived;
}
// case3.
else if (!queue.isEmpty()) {
// Let's consider sum of weights
// case2-1.
if (sumOfWeight + truck > weight) {
queue.add(0); // add nothing
time++;
}
// case2-2.
else {
queue.add(truck);
sumOfWeight += truck;
time++;
break;
}
}
}
}
// have to + bridge_length because the remained trucks also must be arrived
return time + bridge_length; // important
}
}
/**
[Question]
- ํธ๋ญ ์ฌ๋ฌ ๋๊ฐ ์ ํด์ง ์์ผ๋ก ๊ฑด๋
- return ๋ชจ๋ ํธ๋ญ์ด ๋ค๋ฆฌ๋ฅผ '์์๋๋ก ์ต๋จ ์๊ฐ ์์' ๊ฑด๋๋ ค๋ฉด ์ต์ ๋ช ์ด?
[Condition]
- ๋ค๋ฆฌ
- ํธ๋ญ์ด ์ต๋ bridge_length๋ ์ฌ๋ผ๊ฐ ์ ์์ผ๋ฉฐ
- weight ์ดํ๊น์ง์ ๋ฌด๊ฒ๋ฅผ ๊ฒฌ๋ ์ ์์ต๋๋ค
- ๋จ, ๋ค๋ฆฌ์ ์์ ํ ์ค๋ฅด์ง ์์ ํธ๋ญ์ ๋ฌด๊ฒ๋ ๋ฌด์
- bridge_length, weight, truck_weights : 1 ~ 10,000
[Example]
- ํธ๋ญ 2๋ + ๋ฌด๊ฒ ์ด ํฉ 10kg๊น์ง
- ํธ๋ญ [7, 4, 5, 6]
-> ์ต์ 8์ด
**/
Letโs keep it simple always.
Comments powered by Disqus.