码迷,mamicode.com
首页 > 其他好文 > 详细

圆圈中最后剩下的数字

时间:2015-04-05 23:30:58      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

N个人围一圈报数,数到3 退出,最后一个是几号
(1)自定义链表
typedef struct Node
{
    int value;
    struct Node* next;

}Node ,*Link;
Link creat(int n){
    Link node=new Node;
    node->value=n-1;
    Link pre,rear;
    rear=pre=node;
    for(int i=n-2;i>=0;i--){
        node =new Node;
        node->value=i;
        node->next=pre;
        pre=node;    
    }
    rear->next=pre;
    return pre;
}
int LastRemaining(int m,Link list){
    Link p=list,q;
    int i=0;
    while(p->next!=p){
         i++;
         if(i==m-1){
             q=p->next;
             p->next=q->next;
             delete q;
             i=0;
         }
         p=p->next;
    }
    int last=p->value;
    return last;
}
int _tmain(int argc, _TCHAR* argv[])
{
    Link list=creat(5);
    int result=LastRemaining(3,list);
    printf("%d\n",result);
}
(2)使用std::list
int LastRemaining_Solution1(unsigned int n, unsigned int m)
{
    if(n < 1 || m < 1)
        return -1;

    unsigned int i = 0;

    list<int> numbers;
    for(i = 0; i < n; ++ i)
        numbers.push_back(i);

    list<int>::iterator current = numbers.begin();
    while(numbers.size() > 1)
    {
        for(int i = 1; i < m; ++ i)
        {
            current ++;
            if(current == numbers.end())
                current = numbers.begin();
        }

        list<int>::iterator next = ++ current;
        if(next == numbers.end())
            next = numbers.begin();

        -- current;
        numbers.erase(current);
        current = next;
    }

    return *(current);
}
时间O(mn),空间O(n)
// ====================方法2====================
int LastRemaining_Solution2(unsigned int n, unsigned int m)
{
    if(n < 1 || m < 1)
        return -1;

    int last = 0;
    for (int i = 2; i <= n; i ++) 
        last = (last + m) % i;

    return last;
}
时间O(n),空间O(1);

 

圆圈中最后剩下的数字

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4394936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!