2022-5-4 每日一题-leetcode
题目链接:https://leetcode-cn.com/problems/find-the-winner-of-the-circular-game/
个人题解:
- 队列模拟(会比较慢)
- 数学递归,迭代节省空间(对比约瑟夫环)
点击查看代码
class Solution {
public:
int findTheWinner(int n, int k) {
queue<int> q;
for(int i=1;i<=n;i++) q.push(i);
while(q.size()>1){
for(int i=1;i<k;i++){
q.push(q.front());
q.pop();
}
q.pop();
}
return q.front();
}
};
class Solution {
public:
int findTheWinner(int n, int k) {
int res=0;
for(int i=2;i<=n;i++) res=(k+res)%i;
return res+1;
}
};
队列:

迭代:


浙公网安备 33010602011771号