《劍指offer》45:約瑟夫問題

約瑟夫問題

這個問題太經典了,就是n個人圍成一圈,編號依次爲0,1,…,n-1,每m個人取一個人退出遊戲,求最終剩下的人的編號是多少?

思路1:模擬

自己隨便手寫個循環鏈表來模擬(不過寫得太醜啦):

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int LastRemaining_Solution(unsigned int n, unsigned int m) {
        if (n == 0 || m == 0)
            return -1;
        CycleList cList(n);
        ListNode* now = cList.head;
        while (cList.size > 1)
            now = cList.removeMthFromIt(now, m);
        return cList.head->val;
    }

private:
    struct ListNode
    {
        int val;
        ListNode* next;
        ListNode(int n)
        : val(n), next(NULL) {}
    };

    class CycleList {
    public:
        CycleList(unsigned int n) {
            head = new ListNode(0);
            size = n;

            ListNode* last = head;
            for (int i = 1; i < n; ++i) {
                ListNode* now = new ListNode(i);
                last->next = now;
                last = now;
            }
            last->next = head;
        }

        ListNode* removeMthFromIt(ListNode* from, int m) {
            ListNode* last = NULL;
            while (--m > 0) {
                last = from;
                from = from->next;
            }
            last->next = from->next;
            if (from == head)
                head = last;
            // cout << "remove " << from->val << endl;
            delete from;
            --size;
            return last->next;
        }

        ListNode* head;
        int size;
    };
};


int main() {
    cout << Solution().LastRemaining_Solution(5, 3) << endl;

    return 0;
}

思路2:用數學推導規律

這個,看書吧,不做搬運工了~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章