当前位置:网站首页>LeetCode. 剑指offer 62. 圆圈中最后剩下的数
LeetCode. 剑指offer 62. 圆圈中最后剩下的数
2022-07-06 17:52:00 【抠脚的大灰狼】
题目描述
0,1,···,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字(删除后从下一个数字开始计数)。求出这个圆圈里剩下的最后一个数字。
例如,0、1、2、3、4这5个数字组成一个圆圈,从数字0开始每次删除第3个数字,则删除的前4个数字依次是2、0、4、1,因此最后剩下的数字是3。
思路
这是一个著名的数学问题 —— 约瑟夫环。
这里直接贴出解法(没有严格的数学证明,但比较容易理解和记忆)
用时光倒流法,从最后的情况开始,往回推。
借用一位大佬的图:
- 最后一轮(称之为第n轮),只剩一个数字(称之为
x
)时,数组总大小为1,x
的下标为0 - n-1轮中,
x
是安全的,我们把整个环拉成一条无限长的直线,则容易知道,这一轮的起点,到x,有m个数,即x前面有m个数,且这一轮中移除的是x前面的那个数。那么该轮中x
的下标为(m + 0) % 2
(在x前面补上m个数),由于有环,我们取个模。这一轮保留了2个数。 - n-2轮中,上一轮的第一个数被保留了下来,说明n-1轮的第一个数前面有m个数,且该轮移除的是这个数前面的那个数。则在整个数组前面补上m个数,则n-1轮中所有数的下标都要往右移m,所以该轮中
x
的下标为,(((m + 0) % 2) + m) % 3
- …
- 第1轮,还原到初始状态,就能求出
x
在初始轮中的下标
class Solution {
public int lastRemaining(int n, int m) {
// 最后一轮的下标
int x = 0;
for (int i = 2; i <= n; i++) {
x = (x + m) % i;
}
return x;
}
}
公式为: f ( n , m ) = [ f ( n − 1 , m ) + m ] f(n,m) = [f(n-1,m) + m] % n f(n,m)=[f(n−1,m)+m],边界条件为 f ( 1 , m ) = 0 f(1,m)=0 f(1,m)=0
严谨的数学推导,参考:这或许是你能找到的最详细约瑟夫环数学推导! - 知乎
边栏推荐
- Oracle:CDB限制PDB资源实战
- 【C语言进阶篇】指针的8道笔试题
- Neon Optimization: an instruction optimization case of matrix transpose
- The MySQL database in Alibaba cloud was attacked, and finally the data was found
- NEON优化:性能优化经验总结
- [case sharing] basic function configuration of network loop detection
- Force buckle 1037 Effective boomerang
- Receive user input, height BMI, BMI detection small business entry case
- NEON优化:关于交叉存取与反向交叉存取
- [JS] obtain the N days before and after the current time or the n months before and after the current time (hour, minute, second, year, month, day)
猜你喜欢
JTAG debugging experience of arm bare board debugging
Transplant DAC chip mcp4725 to nuc980
黑马笔记---异常处理
[hfctf2020]babyupload session parsing engine
Typical problems of subnet division and super network construction
Make Jar, Not War
Force buckle 1037 Effective boomerang
Lldp compatible CDP function configuration
[100 cases of JVM tuning practice] 05 - Method area tuning practice (Part 2)
LLDP兼容CDP功能配置
随机推荐
docker 方法安装mysql
Neon Optimization: an instruction optimization case of matrix transpose
NEON优化:性能优化常见问题QA
Implementation principle of waitgroup in golang
Neon Optimization: performance optimization FAQ QA
斗地主游戏的案例开发
Yunna - work order management system and process, work order management specification
移植DAC芯片MCP4725驱动到NUC980
云呐-工单管理制度及流程,工单管理规范
力扣1037. 有效的回旋镖
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
Transformation transformation operator
Meet in the middle
Body mass index program, entry to write dead applet project
Taro2.* 小程序配置分享微信朋友圈
Taro中添加小程序 “lazyCodeLoading“: “requiredComponents“,
405 method not allowed appears when the third party jumps to the website
JTAG principle of arm bare board debugging
C language instance_ two
搭建【Redis in CentOS7.x】