1 題目描述
0,1,n-1這n個數字排成一個圓圈,從數字0開始,每次從這個圓圈裏刪除第m個數字。求出這個圓圈裏剩下的最後一個數字。
例如,0、1、2、3、4這5個數字組成一個圓圈,從數字0開始每次刪除第3個數字,則刪除的前4個數字依次是2、0、4、1,因此最後剩下的數字是3。
示例 1:
輸入: n = 5, m = 3
輸出: 3
示例 2:
輸入: n = 10, m = 17
輸出: 2
限制:
1 <= n <= 10^5
1 <= m <= 10^6
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2 解題思路
- 方法一:直接遍歷法
- 方法二:數學法
別人面向對象,面向過程編程。 而我是面向答案編程: 0個人時候遊戲就不存在了, 1個人時候直接獲勝, 所以從2個人開始, 反推公式:f(n,m) = (f(n,m) + m) % i #i爲當前人數
3 解決代碼
- 方法一:直接遍歷法《Java代碼》
class Solution {
public int lastRemaining(int n, int m) {
ArrayList<Integer> res = new ArrayList<>();
for(int i = 0; i < n; i++){
res.add(i);
}
int idx = 0;
while(n > 1){
idx = (idx + m - 1) % n;
res.remove(idx);
n--;
}
return res.get(0);
}
}
- 方法二:數學法
class Solution {
public int lastRemaining(int n, int m) {
int ans = 0;
// 最後一輪剩下2個人,所以從2開始反推
for (int i = 2; i <= n; i++) {
ans = (ans + m) % i;
}
return ans;
}
}