程序員面試題精選100題(14)-圓圈中最後剩下的數字[算法]

題目:n個數字(0,1,…,n-1)形成一個圓圈,從數字0開始,每次從這個圓圈中刪除第m個數字(第一個爲當前數字本身,第二個爲當前數字的下一個數字)。當一個數字刪除後,從被刪除數字的下一個繼續刪除第m個數字。求出在這個圓圈中剩下的最後一個數字。

分析:本題就是有名的約瑟夫環問題。既然題目有一個數字圓圈,很自然的想法是我們用一個數據結構來模擬這個圓圈。在常用的數據結構中,我們很容易想到用環形列表。我們可以創建一個總共有m個數字的環形列表,然後每次從這個列表中刪除第m個元素。

在參考代碼中,我們用STLstd::list來模擬這個環形列表。由於list並不是一個環形的結構,因此每次跌代器掃描到列表末尾的時候,要記得把跌代器移到列表的頭部。這樣就是按照一個圓圈的順序來遍歷這個列表了。

這種思路需要一個有n個結點的環形列表來模擬這個刪除的過程,因此內存開銷爲O(n)。而且這種方法每刪除一個數字需要m步運算,總共有n個數字,因此總的時間複雜度是O(mn)。當mn都很大的時候,這種方法是很慢的。

接下來我們試着從數學上分析出一些規律。首先定義最初的n個數字(0,1,…,n-1)中最後剩下的數字是關於nm的方程爲f(n,m)

在這n個數字中,第一個被刪除的數字是(m-1)%n,爲簡單起見記爲k。那麼刪除k之後的剩下n-1的數字爲0,1,…,k-1,k+1,…,n-1,並且下一個開始計數的數字是k+1。相當於在剩下的序列中,k+1排到最前面,從而形成序列k+1,…,n-1,0,…k-1。該序列最後剩下的數字也應該是關於nm的函數。由於這個序列的規律和前面最初的序列不一樣(最初的序列是從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作一個映射,映射的結果是形成一個從0n-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-1)%n代入得到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;
}


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

轉自:http://zhedahht.blog.163.com/blog/static/2541117420072250322938/

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