78ms O(log n) JAVA Solution


  • 0
    Y
    public class Solution {
        public int lastRemaining(int n) {
            if(n == 1)
                return 1;
            int left = 1;
            int right = n;
            int gap = 1;
            int round = 1;
            while(right - left > gap){
                if(round % 2 != 0){
                    if(((right - left) / gap) % 2 == 0)
                        right -= gap;
                    left += gap;
                }else{
                    if(((right - left) / gap) % 2 == 0)
                        left += gap;
                    right -= gap;
                }
                gap *= 2;
                round++;
            }
            return round % 2 != 0 ? right : left;
        }
    }

Log in to reply
 

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