《劍指offer》孩子們的遊戲(圓圈中最後剩下的數),《劍指offer》圓圈

來源:互聯網
上載者:User

《劍指offer》孩子們的遊戲(圓圈中最後剩下的數),《劍指offer》圓圈

【 聲明:著作權,轉載請標明出處,請勿用於商業用途。  聯絡信箱:libin493073668@sina.com】


題目連結:http://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


題目描述
每年六一兒童節,NowCoder都會準備一些小礼物去看望孤兒院的小朋友,今年亦是如此。HF作為NowCoder的資深元老,自然也準備了一些小遊戲。其中,有個遊戲是這樣的:首先,讓小朋友們圍成一個大圈。然後,他隨機指定一個數m,讓編號為0的小朋友開始報數。每次喊到m的那個小朋友要出列唱首歌,然後可以在礼品箱中任意的挑選礼物,並且不再回到圈中,從他的下一個小朋友開始,繼續0...m-1報數....這樣下去....直到剩下最後一個小朋友,可以不用表演,並且拿到NowCoder名貴的“名偵探柯南”典藏版(名額有限哦!!^_^)。請你試著想下,哪個小朋友會得到這份礼品呢?

思路
這道題最經典的解法就是使用鏈表類比整個過程了,但是其時間複雜度是O(mn),在m比較大的時候並不理想
如果同學們對於約瑟夫環還有更多研究的話,便會知道我們還可以通過數學方法來解決,時間複雜度為O(n),空間複雜度為O(1)


鏈表做法

class Solution{public:int LastRemaining_Solution(unsigned int n, unsigned int m){if(n<1 || m<1)return -1;list<int> num;for(int i = 0; i<n; ++i)num.push_back(i);list<int>::iterator cur = num.begin();while(num.size()>1){for(int i = 1; i<m; ++i){++cur;if(cur == num.end())cur = num.begin();}list<int>::iterator next = ++cur;if(next==num.end())next = num.begin();--cur;num.erase(cur);cur = next;}return *cur;}};

數學做法

class Solution{public:int LastRemaining_Solution(unsigned int n, unsigned int m){if(n<1 || m<1)return -1;int ans = 0;for(int i = 2; i<=n; i++)ans = (ans+m)%i;return ans;}};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.