您的位置:首页 > 其它

圆圈中最后剩下的数字

2017-08-11 20:51 357 查看
题目:
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表