程式員面試題精選(14):圓圈中最後剩下的數字

來源:互聯網
上載者:User
題目:n個數字(0,1,…,n-1)形成一個圓圈,從數字0開始,每次從這個圓圈中刪除第m個數字(第一個為當前數字本身,第二個為當前數位下一個數字)。當一個數字刪除後,從被刪除數位下一個繼續刪除第m個數字。求出在這個圓圈中剩下的最後一個數字。分析:既然題目有一個數字圓圈,很自然的想法是我們用一個資料結構來類比這個圓圈。在常用的資料結構中,我們很容易想到用環形列表。我們可以建立一個總共有m個數位環形列表,然後每次從這個列表中刪除第m個元素。在參考代碼中,我們用STL中std::list來類比這個環形列表。由於list並不是一個環形的結構,因此每次跌代器掃描到列表末尾的時候,要記得把跌代器移到列表的頭部。這樣就是按照一個圓圈的順序來遍曆這個列表了。這種思路需要一個有n個結點的環形列表來類比這個刪除的過程,因此記憶體開銷為O(n)。而且這種方法每刪除一個數字需要m步運算,總共有n個數字,因此總的時間複雜度是O(mn)。當m和n都很大的時候,這種方法是很慢的。接下來我們試著從數學上分析出一些規律。首先定義最初的n個數字(0,1,…,n-1)中最後剩下的數字是關於n和m的方程為f(n,m)。在這n個數字中,第一個被刪除的數字是m%n-1,為簡單起見記為k。那麼刪除k之後的剩下n-1的數字為0,1,…,k-1,k+1,…,n-1,並且下一個開始計數的數字是k+1。相當於在剩下的序列中,k+1排到最前面,從而形成序列k+1,…,n-1,0,…k-1。該序列最後剩下的數字也應該是關於n和m的函數。由於這個序列的規律和前面最初的序列不一樣(最初的序列是從0開始的連續序列),因此該函數不同於前面函數,記為f’(n-1,m)。最初序列最後剩下的數字f(n,m)一定是剩下序列的最後剩下數字f’(n-1,m),所以f(n,m)=f’(n-1,m)。接下來我們把剩下的的這n-1個數位序列k+1,…,n-1,0,…k-1作一個映射,映射的結果是形成一個從0到n-2的序列:k+1    ->    0
k+2    ->    1

n-1    ->    n-k-2
0   ->    n-k-1

k-1   ->   n-2把映射定義為p,則p(x)= (x-k-1)%n,即如果映射前的數字是x,則映射後的數字是(x-k-1)%n。對應的逆映射是p-1(x)=(x+k+1)%n。由於映射之後的序列和最初的序列有同樣的形式,都是從0開始的連續序列,因此仍然可以用函數f來表示,記為f(n-1,m)。根據我們的映射規則,映射之前的序列最後剩下的數字f’(n-1,m)= p-1 [f(n-1,m)]=[f(n-1,m)+k+1]%n。把k=m%n-1代入得到f(n,m)=f’(n-1,m)=[f(n-1,m)+m]%n。經過上面複雜的分析,我們終於找到一個遞迴的公式。要得到n個數位序列的最後剩下的數字,只需要得到n-1個數位序列的最後剩下的數字,並可以依此類推。當n=1時,也就是序列中開始只有一個數字0,那麼很顯然最後剩下的數字就是0。我們把這種關係表示為:         0                  n=1
f(n,m)={
         [f(n-1,m)+m]%n     n>1儘管得到這個公式的分析過程非常複雜,但它用遞迴或者迴圈都很容易實現。最重要的是,這是一種時間複雜度為O(n),空間複雜度為O(1)的方法,因此無論在時間上還是空間上都優於前面的思路。思路一的參考代碼:///////////////////////////////////////////////////////////////////////
// n integers (0, 1, ... n - 1) form a circle. Remove the mth from
// the circle at every time. Find the last number remaining
// Input: n - the number of integers in the circle initially
//        m - remove the mth number at every time
// Output: the last number remaining when the input is valid,
//         otherwise -1
///////////////////////////////////////////////////////////////////////
int LastRemaining_Solution1(unsigned int n, unsigned int m)
{
      // invalid input
      if(n < 1 || m < 1)
            return -1;

      unsigned int i = 0;

      // initiate a list with n integers (0, 1, ... n - 1)
      list<int> integers;
      for(i = 0; i < n; ++ i)
            integers.push_back(i);

      list<int>::iterator curinteger = integers.begin();
      while(integers.size() > 1)
      {
            // find the mth integer. Note that std::list is not a circle
            // so we should handle it manually
            for(int i = 1; i < m; ++ i)
            {
                  curinteger ++;
                  if(curinteger == integers.end())
                        curinteger = integers.begin();
            }

            // remove the mth integer. Note that std::list is not a circle
            // so we should handle it manually
            list<int>::iterator nextinteger = ++ curinteger;
            if(nextinteger == integers.end())
                  nextinteger = integers.begin();

            -- curinteger;
            integers.erase(curinteger);
            curinteger = nextinteger;
      }

      return *(curinteger);
}思路二的參考代碼:///////////////////////////////////////////////////////////////////////
// n integers (0, 1, ... n - 1) form a circle. Remove the mth from
// the circle at every time. Find the last number remaining
// Input: n - the number of integers in the circle initially
//        m - remove the mth number at every time
// Output: the last number remaining when the input is valid,
//         otherwise -1
///////////////////////////////////////////////////////////////////////
int LastRemaining_Solution2(int n, unsigned int m)
{
      // invalid input
      if(n <= 0 || m < 0)
            return -1;

      // if there are only one integer in the circle initially,
      // of course the last remaining one is 0
      int lastinteger = 0;

      // find the last remaining one in the circle with n integers
      for (int i = 2; i <= n; i ++) 
            lastinteger = (lastinteger + m) % i;

      return lastinteger;
}如果對兩種思路的時間複雜度感興趣的讀者可以把n和m的值設的稍微大一點,比如十萬這個數量級的數字,啟動並執行時候就能明顯感覺出這兩種思路寫出來的代碼時間效率大不一樣。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.