Skip to content

Commit 84152b2

Browse files
add a solution for 1823
1 parent 8b08ebf commit 84152b2

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/main/java/com/fishercoder/solutions/_1823.java

+23
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.fishercoder.solutions;
22

33
import java.util.ArrayList;
4+
import java.util.Deque;
5+
import java.util.LinkedList;
46
import java.util.List;
57

68
public class _1823 {
@@ -19,4 +21,25 @@ public int findTheWinner(int n, int k) {
1921
return list.get(0);
2022
}
2123
}
24+
25+
public static class Solution2 {
26+
/**
27+
* My completely original solution: use a double linked list to keep moving people from
28+
* the tail of the queue to the head of the queue until there's only one person in the queue who is the winner.
29+
*/
30+
public int findTheWinner(int n, int k) {
31+
Deque<Integer> doublyLinkedList = new LinkedList<>();
32+
for (int i = 1; i <= n; i++) {
33+
doublyLinkedList.addFirst(i);
34+
}
35+
while (doublyLinkedList.size() > 1) {
36+
int counter = 1;
37+
while (counter++ < k) {
38+
doublyLinkedList.addFirst(doublyLinkedList.pollLast());
39+
}
40+
doublyLinkedList.pollLast();
41+
}
42+
return doublyLinkedList.getLast();
43+
}
44+
}
2245
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._1823;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _1823Test {
10+
private static _1823.Solution1 solution1;
11+
private static _1823.Solution2 solution2;
12+
private static int expected;
13+
14+
@BeforeClass
15+
public static void setup() {
16+
solution1 = new _1823.Solution1();
17+
solution2 = new _1823.Solution2();
18+
}
19+
20+
@Test
21+
public void test1() {
22+
expected = 1;
23+
assertEquals(expected, solution1.findTheWinner(6, 5));
24+
assertEquals(expected, solution2.findTheWinner(6, 5));
25+
}
26+
27+
}

0 commit comments

Comments
 (0)