2022-5-4 每日一题-leetcode

题目链接:https://leetcode-cn.com/problems/find-the-winner-of-the-circular-game/

个人题解:

  1. 队列模拟(会比较慢)
  2. 数学递归,迭代节省空间(对比约瑟夫环)
点击查看代码
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;
    }
};

队列:
image

迭代:
image

posted @ 2022-05-04 11:04  黑VS白-清墨  阅读(21)  评论(0)    收藏  举报