当前位置:网站首页>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
严谨的数学推导,参考:这或许是你能找到的最详细约瑟夫环数学推导! - 知乎
边栏推荐
- C语言实例_4
- What does security capability mean? What are the protection capabilities of different levels of ISO?
- Js逆向——捅了【马蜂窝】的ob混淆与加速乐
- JTAG debugging experience of arm bare board debugging
- 2022 Google CTF SEGFAULT LABYRINTH wp
- Make Jar, Not War
- UI control telerik UI for WinForms new theme - vs2022 heuristic theme
- 域分析工具BloodHound的使用说明
- 【案例分享】网络环路检测基本功能配置
- JTAG principle of arm bare board debugging
猜你喜欢

阿里云中mysql数据库被攻击了,最终数据找回来了

AI 从代码中自动生成注释文档

How to manage distributed teams?

【C语言进阶篇】指针的8道笔试题

Boot - Prometheus push gateway use

子网划分、构造超网 典型题

Body mass index program, entry to write dead applet project

Asset security issues or constraints on the development of the encryption industry, risk control + compliance has become the key to breaking the platform

Js逆向——捅了【马蜂窝】的ob混淆与加速乐

Tensorflow GPU installation
随机推荐
NEON优化:性能优化常见问题QA
C语言实例_3
Receive user input, height BMI, BMI detection small business entry case
C# 计算农历日期方法 2022
Lldp compatible CDP function configuration
LeetCode:1175. 质数排列
Asset security issues or constraints on the development of the encryption industry, risk control + compliance has become the key to breaking the platform
Transformation transformation operator
分享一个通用的so动态库的编译方法
1123. 最深叶节点的最近公共祖先
boot - prometheus-push gateway 使用
Using the entry level of DVA in taro3.*
JTAG debugging experience of arm bare board debugging
Taro 小程序开启wxml代码压缩
Analysis of mutex principle in golang
Dark horse notes - create immutable sets and streams
黑马笔记---创建不可变集合与Stream流
ESP Arduino (IV) PWM waveform control output
Make Jar, Not War
2022 Google CTF SEGFAULT LABYRINTH wp