O(log n) Java solution


  • 0
    S
    public class Solution {
        public int lastRemaining(int n) {
            List<Boolean> carry = new ArrayList<Boolean>();
            while (n > 1) {
                //left to right  1 2 3 4 5 6 -> 2 4 6 -> 1 2 3 
                carry.add(true);
                n /= 2;
                if (n == 1) break;;
                if (n % 2 == 1) {
                     //right to left   1 2 3 4 5 6 7 -> 2 4 6 -> 1 2 3
                    carry.add(true);
                    n /= 2;
                } else {
                    //right to left  1 2 3 4 5 6 -> 1 3 5 -> 1 2 3
                    n /= 2;
                    carry.add(false);
                }
            }
            int r = 1;
            for (int i = carry.size() - 1; i >= 0; i--) {
                if (carry.get(i) == true) {
                    r *= 2;
                } else {
                    r = r * 2 -1;   
                }
            }
            return r;
        }
    }
    

Log in to reply
 

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