当前位置:网站首页>【剑指 Offer】62. 圆圈中最后剩下的数字
【剑指 Offer】62. 圆圈中最后剩下的数字
2022-07-05 16:22:00 【LuZhouShiLi】
剑指 Offer 62. 圆圈中最后剩下的数字
题目
0,1,···,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字(删除后从下一个数字开始计数)。求出这个圆圈里剩下的最后一个数字。
例如,0、1、2、3、4这5个数字组成一个圆圈,从数字0开始每次删除第3个数字,则删除的前4个数字依次是2、0、4、1,因此最后剩下的数字是3。
思路
- 创建一个list 模拟环形链表
- 将元素全部添加到list中
- 每次取m步。删除元素,注意取余操作
代码
class Solution {
public int lastRemaining(int n, int m) {
// 创建一个环形链表模拟圆圈
ArrayList<Integer> list = new ArrayList<>(n);
for(int i = 0; i < n; i++)
{
list.add(i);
}
int idx = 0;
while(n > 1)
{
idx = (idx + m - 1) % n;// 每次走M步 取余 因为是环形
list.remove(idx);
n--;
}
return list.get(0);
}
}
边栏推荐
- Cs231n notes (bottom) - applicable to 0 Foundation
- 树莓派4b安装Pytorch1.11
- [echart] resize lodash 实现窗口缩放时图表自适应
- How does win11 change icons for applications? Win11 method of changing icons for applications
- Sentinel-流量防卫兵
- How can programmers improve their situation?
- C# TCP如何设置心跳数据包,才显得优雅呢?
- 二叉树相关OJ题
- Deep dive kotlin synergy (XXI): flow life cycle function
- sqlserver 做cdc 要对数据库性能有什么要求么
猜你喜欢
随机推荐
【学术相关】多位博士毕业去了三四流高校,目前惨不忍睹……
中国广电正式推出5G服务,中国移动赶紧推出免费服务挽留用户
Android privacy sandbox developer preview 3: privacy, security and personalized experience
Spring Festival Limited "forget trouble in the year of the ox" gift bag waiting for you to pick it up~
有序链表集合求交集 方法 总结
Flet教程之 12 Stack 重叠组建图文混合 基础入门(教程含源码)
Games101 notes (I)
"21 days proficient in typescript-3" - install and build a typescript development environment md
Jarvis OJ simple network management protocol
Hiengine: comparable to the local cloud native memory database engine
Raspberry pie 4B installation pytorch1.11
How was the middle table destroyed?
Basic introduction to the control of the row component displaying its children in the horizontal array (tutorial includes source code)
Facing new challenges and becoming a better self -- attacking technology er
Jarvis OJ 远程登录协议
面对新的挑战,成为更好的自己--进击的技术er
Enter a command with the keyboard
Jarvis OJ Flag
yarn 常用命令
China Radio and television officially launched 5g services, and China Mobile quickly launched free services to retain users




![[729. My Schedule i]](/img/e3/32914227d00cf7595ee850e60f2b72.png)




