我是靠谱客的博主 孝顺棒棒糖,这篇文章主要介绍LeetCode 剑指 offer 62 约瑟夫环,现在分享给大家,希望可以做个参考。

     这题考察的是约瑟夫环,本人在面试中也有遇到,数学公式的方法请参照https://www.cnblogs.com/nxf-rabbit75/p/10707989.html

     本人使用的是单向循环链表的方法,但是超时了,代码如下:

struct num{
    int val;
    struct num* next;
    num():val(0), next(nullptr){}
};
class Solution {
public:
    int lastRemaining(int n, int m) {
        int i = 0;
        struct num* head = new num();
        head -> val = 0;
        struct num* trans = head; 

        for(i = 1; i < n; i++){
            struct num* temp = new num();
            temp -> val = i;
            trans -> next = temp;
            trans = temp;
        }

        trans -> next = head;
        trans = head;

        int clock = 1;

        while(trans -> next != trans){
            if(clock != m){
                trans = trans -> next;
                clock++;
            }else{
                clock = 1;//注意下面删除操作的技巧,O(1)时间复杂度删除
                head = trans -> next;
                trans -> val = head -> val;
                trans -> next = head -> next;
                delete head;            
            }
        }

        return trans -> val;
    }
};

 

最后

以上就是孝顺棒棒糖最近收集整理的关于LeetCode 剑指 offer 62 约瑟夫环的全部内容,更多相关LeetCode内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(136)

评论列表共有 0 条评论

立即
投稿
返回
顶部