Sword refers to Offer 62-the last remaining number in the circle C++


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

Insert picture description here

Solution array simulation

Will time out

Mathematical inversion

The powerful solution
Insert picture description here
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
Insert picture description here
seen that each step backwards from N-1 to N does nothing more than two things.

  1. 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.
  2. 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;
    }
};

Insert picture description here
Time complexity O(N)
Space complexity O(1)

Guess you like

Origin blog.csdn.net/qq_42883222/article/details/112788384