[Problem Description] face questions 62. The last remaining digital circle
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
[Thinking] answer
1. Violence Act
- Element inserted into the list
- Each move m-1, where the deleted element, list length n-1
time complexity: O (^ 2 N) space complexity: O (N)
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;
list.remove(idx);
n--;
}
return list.get(0);
}
作者:sweetieeyi
链接:https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/solution/javajie-jue-yue-se-fu-huan-wen-ti-gao-su-ni-wei-sh/
2. Mathematical Methods
- Josephus
- push down
time complexity of O (N)
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;
}
}
作者:sweetieeyi
链接:https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/solution/javajie-jue-yue-se-fu-huan-wen-ti-gao-su-ni-wei-sh/
【to sum up】
- VS ArrayList the LinkedList
the LinkedList time complexity of O (nm) to delete the specified node O (n) (traverse from beginning to end) to access a large number of non-continuous address -> timeout
ArrayList time complexity of O (n ^ 2) Remove the specified element O (n) (need to move) contiguous space of memory copy -> marginal
- Mathematical formulas without having to remember the key is to master the derivation
Link: https: //leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/solution/javajie-jue-yue-se-fu-huan- wen-ti-gao-su-ni-wei-sh /