圆圈中最后剩下的数字

题目:
0,1,...,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。求这个圆圈里剩下的最后一个数字。

分析:
1.利用环形链表模拟圆圈求解。
2.利用删除之后的规律求解。

环形链表:

class Solution
{
public:
    int LastRemaining_Soultion( int n, int m )
    {
        if ( n <= 0 || m <= 0 )
            return 0;
        list<int> circleList;
        list<int>::iterator circleIter;
        list<int>::iterator nextIter;
        int count = 0;
        for ( int i = 0; i < n; i++ )
        {
            circleList.push_back( i );
        }
        circleIter = circleList.begin();
        while ( circleList.size() > 1 )
        {
            if ( circleIter == circleList.end() )
            {
                circleIter = circleList.begin();
            }
            count++;
            nextIter = ++circleIter;
            if ( count%m == 0 )
            {
                circleList.erase( --circleIter );
            }
            circleIter = nextIter;
        }
        return circleList.front();
    }
};

int main( void )
{
    Solution sos;
    cout << sos.LastRemaining_Soultion( 20, 30 ) << endl;
    return 0;
}

规律:这个看的不是很懂,具体规律推导参考《剑指offer》面试题45:

class Solution
{
public:
    int LastRemaining_Solution( int n, 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值