作者:AD518最丶设计 | 来源:互联网 | 2023-09-16 18:31
题目链接:https:leetcode-cn.comproblemsfind-the-winner-of-the-circular-game个人题解:队列模拟(会比较慢)数学递归,
题目链接:https://leetcode-cn.com/problems/find-the-winner-of-the-circular-game/
个人题解:
- 队列模拟(会比较慢)
- 数学递归,迭代节省空间(对比约瑟夫环)
点击查看代码
class Solution {
public:
int findTheWinner(int n, int k) {
queue q;
for(int i=1;i<=n;i++) q.push(i);
while(q.size()>1){
for(int i=1;i q.push(q.front());
q.pop();
}
q.pop();
}
return q.front();
}
};
class Solution {
public:
int findTheWinner(int n, int k) {
int res=1;
for(int i=2;i<=n;i++) res=(k+res-1)%i+1;
return res;
}
};
队列:
迭代: