File tree 2 files changed +50
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
3
import java .util .ArrayList ;
4
+ import java .util .Deque ;
5
+ import java .util .LinkedList ;
4
6
import java .util .List ;
5
7
6
8
public class _1823 {
@@ -19,4 +21,25 @@ public int findTheWinner(int n, int k) {
19
21
return list .get (0 );
20
22
}
21
23
}
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
+ }
22
45
}
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments