1823 - Find the Winner of the Circular Game
JAVA
class Solution {
public int findTheWinner(int n, int k) {
if (n == 1) {
return 1;
}
int ans = (findTheWinner(n - 1, k) + k) % n;
return ans == 0 ? n : ans;
}
}C++
class Solution {
public:
int findTheWinner(int n, int k) {
set<int> s;
for (int i = 1; i <= n; ++i) {
s.insert(i);
}
auto it = begin(s);
while (s.size() > 1) {
for (int i = 1; i < k; ++i) {
it = it == prev(s.end()) ? begin(s) : next(it);
}
auto j = it == prev(s.end()) ? begin(s) : next(it);
s.erase(it);
it = j;
}
return *s.begin();
}
};
Comments
Post a Comment