程序员面试题精选100题(14)-圆圈中最后剩下的数字[算法] 【约瑟夫环问题,经典】

约瑟夫环问题

方法一、从前向后,时间复杂度为O(mn)

方法二、规律

                    0                  n=1
f(n,m)={
                    [f(n-1,m)+m]%n     n>1

 

========================================================================================================================

本文转自: http://zhedahht.blog.163.com/blog/static/2541117420072250322938/

题目: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);
}

思路一C语言代码实现,本代码中用的是双向链表实现的。

#include "StdAfx.h"
#include <stdio.h>
#include <stdlib.h>
struct _Node
{
    int data;
    struct _Node *next;
};
typedef struct _Node node_t;
typedef struct _Linklist
{
    node_t * phead;
    node_t * ptail;
    int len;
}Linklist;
static node_t * GetNode( int i )    // 新建并初始化节点
{
    node_t *pNode;
    pNode = ( node_t * )malloc( sizeof( node_t ) );
    if(!pNode)
    {
        printf("Error,the memory is not enough!\n");
        exit(-1);
    }
    pNode -> data = i;
    pNode -> next = NULL;
    return pNode;
}
void init_list( Linklist *plist )    // 用第一个节点初始化循环单链表
{
    node_t *p;
    p = GetNode( 1 );
//  printf("The New Node is: %d\n", p -> data);   // **** TEST ****
    plist -> phead = p;
    plist -> ptail = p;
    p -> next = plist -> phead;
    plist -> len = 1;
}
static void Create_List( Linklist *plist, int n )    // 把其余数据添加到循环单链表中
{
    int i = 0;
    node_t *pNew;
    for(i=2;i<=n;i++)
    {
    pNew = GetNode( i );
    /******** TEST ********
    printf("The New Node is: %d\n", pNew -> data);
    ******** TEST ********/
        plist -> ptail -> next = pNew;
    plist -> ptail = pNew;
    pNew -> next = plist -> phead;
    plist -> len ++;
    }
    printf("Completes the e-way circulation chain table the foundation!\n");
}
void Print_List( Linklist *plist )    // 输出链表内容
{
    node_t *pCur = plist -> phead;
    do
    {
        printf("The %d person.\n", pCur -> data );
    pCur = pCur -> next;
    }while( pCur != plist -> phead );
    printf("The length of the List: %d\n", plist -> len );
}
void joseph( Linklist *plist, int m )    //约瑟夫回环函数实现
{
    node_t *pPre = plist -> ptail;
    node_t *pCur = plist -> phead;
    int i;
    while( plist -> len != 1 )
    {
        i = 0;
    while( i < m-1 )
    {
        pPre = pPre -> next;
        i ++;
    }
    pCur = pPre -> next;
    pPre -> next = pCur -> next;
    free( pCur );
    plist -> len --;
    }
    printf("The last one is: %d\n", pPre -> data );
}
int main()
{
    int n = 0;
    printf("Please input the Length of the Circle list: ");
    scanf("%d", &n );
    int m = 0;
    printf("Please input the Stop point: ");
    scanf("%d", &m );
    Linklist pList;
    init_list( &pList );
    Create_List( &pList, n );
    Print_List( &pList );
    joseph( &pList, m );
    return 0;
}


 

思路二的参考代码:

///
// 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的值设的稍微大一点,比如十万这个数量级的数字,运行的时候就能明显感觉出这两种思路写出来的代码时间效率大不一样。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值