-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathFindTheWinnerOfTheCircularGame.java
70 lines (60 loc) · 1.68 KB
/
FindTheWinnerOfTheCircularGame.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package problems.leetcode;
// https://leetcode.com/problems/find-the-winner-of-the-circular-game/
public class FindTheWinnerOfTheCircularGame {
// 0, 1, 2, 3, 4, 5
// 1, 2, 3, 4, 5, 6
// n = 6, k = 3
// 1, 2, 3, 4, 5, 6
// 1, 2, -, 4, 5, 6
// 1, 2, -, 4, 5, -
// 1, 2, -, -, 5, -
// 1, -, -, -, 5, -
// 1, -, -, -, -, -
//
// n = 6, k = 4
// 1, 2, 3, 4, 5, 6
// 1, 2, 3, -, 5, 6
// 1, -, 3, -, 5, 6
// -, -, 3, -, 5, 6
// -, -, -, -, 5, 6
// -, -, -, -, 5, -
//
// n = 7, k = 2
// 1, 2, 3, 4, 5, 6, 7
// 1, -, 3, 4, 5, 6, 7
// 1, -, 3, -, 5, 6, 7
// 1, -, 3, -, 6, -, 7
// -, -, 3, -, 6, -, 7
// -, -, 3, -, -, -, 7
// -, -, -, -, -, -, 7
public static int findTheWinner(int n, int k) {
int[] players = new int[n];
for (int i = 0; i < n; i++) {
players[i] = i + 1;
}
int current = 0;
for (int remaining = n - 1; remaining > 0; remaining--) {
for (int move = k; move > 0;) {
if (players[current++] != 0) {
move--;
}
if (current == n) {
current = 0;
}
}
players[((current - 1) + n) % n] = 0;
}
for (int i = 0; i < n; i++) {
if (players[i] != 0) {
return players[i];
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(findTheWinner(5, 2));
System.out.println(findTheWinner(6, 3));
System.out.println(findTheWinner(6, 4));
System.out.println(findTheWinner(7, 2));
}
}