JAVA:Easy to understand! O(logN) solution beats 97.98% submissions


  • 0
    W
        public int lastRemaining(int n) {
            if (n == 1) {
                return 1;
            } else if (n % 2 == 1) {
                return lastRemaining(n - 1);
            } else {
                return (n + 2 - 2 * lastRemaining(n / 2));
            }
        }
    

    case 1 :
    return 1

    case : singular
    same with case singular - 1
    return lastRemaining(singular - 1)

    case : even
    find relationship bewteen even and half even(consider inverse!)
    return even + 2 - 2*lastRemaining(half_even)


Log in to reply
 

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