LeetCode 390. Elimination Game

  • 题目描述

There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.

Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.

We keep repeating the steps again, alternating left to right and right to left, until a single number remains.

Find the last number that remains starting with a list of length n.

Example:

Input:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6

Output:
6
  • 解题思路
    一个很容易观察到的变化规律就是步长信息,那我们就首先得到步长的规律。观察第一列的步长为2,第二列的步长为4(相隔元素),第三列元素为8(假设存在10 11 12 第二列元素就变成 2 4 6 8 10 12 第三列就变成 2 6 10),也就是说步数在每轮循环中是上一轮的两倍。我们再来观察元素个数递减规律,发现元素个数是按1/2的速度递减的。当递减元素个数减少到1时,就得到了最终的剩余元素。最难的部分就是追踪每次的头部元素,很容易观察到的一个结论是,从左侧开始的头部元素都是上一次的头部元素加上步长。对于从右侧开始的迭代过程,则分为两种情况,一种情况是左侧头部元素不变,一种情况是左侧头部元素为上次迭代的头部元素加步长,对于后一种情况,我们容易观察到的一点是,在剩余元素是奇数个时,头部元素会发生改变,否则不变。
  • 代码
class Solution {
    public int lastRemaining(int n) {
        boolean left = true;
        int remaining = n;
        int step = 1;
        int head = 1;
        while (remaining > 1) {
            if (left || remaining % 2 ==1) {
                head = head + step;
            }
            remaining = remaining / 2;
            step = step * 2;
            left = !left;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40275300/article/details/88360352