2020/2/5
How much i is equal to in the for loop of the second brush , that is, the length is restored to the case of i,
so it goes to n of course
Title description
Solution array simulation
Will time out
Mathematical inversion
The powerful solution
with pictures and texts is derived in this way, taking the next person each time as the initial node of the new array, so the last time must be 0, then the next step is how to deduce the just by using 0 the last time. The index of the array at the beginning.
Let’s derive from F(8,3) to F(7,3). It can be
seen that each step backwards from N-1 to N does nothing more than two things.
- Make up
the person who was killed the Nth time. This person must be made up at the end of the array, because our N-1th array starts with the m + 1th element and continues to the person who was killed. So the person who was killed is now the tail. - Move all elements of the N-1 array to the right by m places.
Because the N-1 array starts with the m + 1 subscript of N times, to change back to the original look is to move the first element back to the original Position, move right m times,
so the derivation formula of
F(N) is F(N) = 0 N=1
F(N) = (F(N-1) + M)% N N>=1
class Solution {
public:
int lastRemaining(int n, int m) {
//活下来的人最后一次在0号位
int ans = 0;
//从倒数第二次开始倒推
for(int i = 2; i <= n; i ++) {
ans = (ans + m) % i;
}
return ans;
}
};
Time complexity O(N)
Space complexity O(1)