题目描述:
n个人围成一圈,报到第k个数的人出局,重复报数,最后剩下的一个人是获胜者。
数据结构:队列。
解答1(繁琐)
:参考了百科“约瑟夫问题”中c++的思路。
超时
class Solution {
public int findTheWinner(int n, int k) {
List<Integer> queue = new ArrayList<Integer>();
if(n == 1)return 1;
for(int i = 1;i <= n;i++){
queue.add(i);
}
while(queue.size() > 1){
for(int i = 0;i < k - 1;i++){
queue.add(queue.remove(0));
}
queue.remove(0);
}
return queue.get(0);
}
}
解答2
复杂度更低的解法:用下标变化代替list的频繁移动。
勉强通过。
class Solution {
public int findTheWinner(int n, int k) {
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(i);
}
int idx = 0;
while (n > 1) {