圆圈中最后剩下的数字
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; } };
相关文章推荐
- 圆圈中最后剩下的数字
- 【转帖】圆圈中最后剩下的数字
- 剑指offer-面试题45-圆圈中最后剩下的数字
- 编程算法 - 圆圈中最后剩下的数字(循环链表) 代码(C++)
- 圆圈中最后剩下的数字
- 《剑指offer》面试题45 圆圈中最后剩下的数字(Java版本)
- Q45:圆圈中最后剩下的数字
- 圆圈中最后剩下的数字
- 圆圈中剩下的最后的数字--20150928
- 圆圈中最后剩下的数字----Joseph环
- 《面试题精选》14.圆圈中最后剩下的数字
- 剑指offer-44 圆圈中最后剩下的数字
- 面试题45:圆圈中最后剩下的数字
- 面试题45:圆圈中最后剩下的数字
- IT公司100题-18-圆圈中最后剩下的数字
- 程序员面试题精选100题(14)-圆圈中最后剩下的数字[算法]
- [剑指offer] 圆圈中最后剩下的数字
- 圆圈中最后剩下的数字
- 圆圈中最后剩下的数字
- 圆圈中最后剩下的数字(约瑟夫环问题)