Java recursive way


  • 0
    Z

    public int lastRemaining(int n) {
    if (n == 1) {
    return 1;
    }
    return (n / 2 + 1 - lastRemaining(n / 2)) * 2;
    }

    1. After every step, we actually boil down the n problem to n / 2 problem, but in opposite direction;
    2. Last remain of n from left to right + last remaining of n from right to left = n + 1.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.