圆圈中最后剩下的数
来源:互联网 发布:java web是做什么的 编辑:程序博客网 时间:2024/06/07 06:52
题目描述:0,1,…,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。求出这个圆圈里城下的最后一个数字。
举例如下图所示:
书上提供了两种解法,第一种常规地用环形链表模拟圆圈,循环删除返回剩下的最后一个。第二种根据数学分析推导递归公式,计算得数。然鹅。。比较好的第二种方法好像不太懂呢
模拟圆圈的思路:用list构造链表,用迭代器扫描,当扫描到链表尾部时,移到头部,实现环形链表。
代码:
class Solution {public: int LastRemaining_Solution(int n, int m) { if (n < 1 || m < 1) return -1; list<int> numbers; for (int i = 0; i < n; i++) { numbers.push_back(i); } list<int>::iterator current = numbers.begin(); while (numbers.size() > 1) { //下面循环从i=1开始,因为要实现循环m-1次 for (int i = 1; i < m; i++) { current++; //实现把链表连成环 if (current == numbers.end()) current = numbers.begin(); } //这里要用到++current赋给next是因为迭代器不允许+1操作,只能自加,后面再自减回来 list<int>::iterator next = ++current; if (next == numbers.end()) next = numbers.begin(); --current; numbers.erase(current); current = next; } return (*current); }};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
阅读全文
0 0
- 圆圈中最后剩下的数
- 圆圈中最后剩下的数
- 圆圈中最后剩下的数
- 圆圈中最后剩下的数
- 46.圆圈中最后剩下的数
- 圆圈中最后剩下的数
- 46、圆圈中最后剩下的数
- 圆圈中最后剩下的数
- Python :圆圈中最后剩下的数
- 圆圈中最后剩下的数
- 圆圈中最后剩下的一个数
- 圆圈中最后剩下的数
- 圆圈中最后剩下的数
- 孩子们的游戏(圆圈中最后剩下的数)
- 孩子们的游戏(圆圈中最后剩下的数)
- 孩子们的游戏(圆圈中最后剩下的数)
- 孩子们的游戏(圆圈中最后剩下的数)链表
- 牛客网 | 孩子们的游戏(圆圈中最后剩下的数)
- 使用MongoDB类操作MongoDB数据库总结
- (VS2010)MFC中List Control基本用法
- OnCtlColor函数的用法
- angular 4 表单
- 原生js实现对select下拉列表的内容过滤
- 圆圈中最后剩下的数
- 基本VLAN特性配置与管理——5
- Shader-数据类型
- 线程学习笔记
- JAVAEE——网上订购子系统的开发(终)
- Android get请求出现java.net.ProtocolException: Unexpected status line
- JPA学习(四):java持久化查询语言JPQL--高级应用及语法
- Flink 1.3 Table and SQL Beta Java API 总结
- Spring集成Memcached三种方式