- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1823.java
46 lines (43 loc) · 1.54 KB
/
_1823.java
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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.ArrayList;
importjava.util.Deque;
importjava.util.LinkedList;
importjava.util.List;
publicclass_1823 {
publicstaticclassSolution1 {
publicintfindTheWinner(intn, intk) {
List<Integer> list = newArrayList<>(n);
for (inti = 0; i < n; i++) {
list.add(i + 1);
}
intstartIndex = 0;
while (list.size() != 1) {
intremoveIndex = (startIndex + k - 1) % list.size();
list.remove(removeIndex);
startIndex = removeIndex;
}
returnlist.get(0);
}
}
publicstaticclassSolution2 {
/*
* My completely original solution: use a double linked list to keep moving (k - 1) people from
* the tail of the queue to the head of the queue, and then remove the kth person,
* until there's only one person in the queue who is the winner.
*/
publicintfindTheWinner(intn, intk) {
Deque<Integer> doublyLinkedList = newLinkedList<>();
for (inti = 1; i <= n; i++) {
doublyLinkedList.addFirst(i);
}
while (doublyLinkedList.size() > 1) {
intcounter = 1;
while (counter++ < k) {
doublyLinkedList.addFirst(doublyLinkedList.pollLast());
}
doublyLinkedList.pollLast();
}
returndoublyLinkedList.getLast();
}
}
}