当前位置:网站首页>【剑指 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);
}
}
边栏推荐
- Explain in detail the functions and underlying implementation logic of the groups sets statement in SQL
- JSON转MAP前后数据校验 -- 自定义UDF
- Learnopongl notes (I)
- File operation --i/o
- Combined use of vant popup+ other components and pit avoidance Guide
- Jarvis OJ 简单网管协议
- [deep learning] [original] let yolov6-0.1.0 support the txt reading dataset mode of yolov5
- Jarvis OJ shell traffic analysis
- PHP strict mode
- [61dctf]fm
猜你喜欢
composer安装报错:No composer.lock file present.
【刷题篇】有效的数独
如何将mysql卸载干净
Jarvis OJ Telnet Protocol
How does win11 change icons for applications? Win11 method of changing icons for applications
单商户 V4.4,初心未变,实力依旧!
Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要
Jarvis OJ shell流量分析
Bs-xx-042 implementation of personnel management system based on SSM
有序链表集合求交集 方法 总结
随机推荐
Today's sleep quality record 79 points
Explain in detail the functions and underlying implementation logic of the groups sets statement in SQL
微信公众号网页授权登录实现起来如此简单
If you can't afford a real cat, you can use code to suck cats -unity particles to draw cats
Facing new challenges and becoming a better self -- attacking technology er
Jarvis OJ Webshell分析
Android privacy sandbox developer preview 3: privacy, security and personalized experience
Summary of methods for finding intersection of ordered linked list sets
Twig数组合并的写法
Seaborn draws 11 histograms
二叉树相关OJ题
怎样在电脑上设置路由器的WiFi密码
挖财股票开户安全吗?怎么开股票账户是安全?
File operation --i/o
【729. 我的日程安排錶 I】
sqlserver 做cdc 要对数据库性能有什么要求么
养不起真猫,就用代码吸猫 -Unity 粒子实现画猫咪
The memory of a Zhang
Binary tree related OJ problems
Learnopongl notes (II) - Lighting