Easy Java Solution O(log n)


  • 0
    P

    The mainly difference between 1,2,3,4 and 2,4,6,8 is that the elements in the second array is twice as much as those in the first array.
    And that is actually the core idea of my solution.

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

Log in to reply
 

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