【LeetCode】390. Elimination Game 消除游戏(Medium)(JAVA)

【LeetCode】390. Elimination Game 消除游戏(Medium)(JAVA)

题目地址: https://leetcode.com/problems/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

题目大意

给定一个从1 到 n 排序的整数列表。
首先,从左到右,从第一个数字开始,每隔一个数字进行删除,直到列表的末尾。
第二步,在剩下的数字中,从右到左,从倒数第一个数字开始,每隔一个数字进行删除,直到列表开头。
我们不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。
返回长度为 n 的列表中,最后剩下的数字。

解题方法

1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6

1 2 3 4 5 6 7 8 9
1 2 3 4 -> k * 2
1 2 -> (k * 2 - 1) * 2
2 -> (2 * 2 - 1) * 2
  1. 可以采用递归的方法
  2. 从左到右:其实第一次就是删除了所有的奇数,只剩下了偶数,如果把所有的数都除以 2,会发现还是在 [1, n / 2] 内找到元素 k ,然后结果 k * 2 即可
  3. 从右到左:这时候,如果数量是偶数个,就是删除了所有的偶数位,留下奇数,如:总共十个数 n = 10,剩下的是 [1, 3, 5, 7, 9] -> [1 * 2 - 1, 2 * 2 - 1, …, 5 * 2 - 1], 可以转换成 1,n/2 内找到元素 k ,然后结果 k * 2 - 1 即可
  4. 从右到左:如果数量是奇数个,就是删除了所有的奇数位,留下偶数:把所有的数都除以 2,会发现还是在 [1, n / 2] 内找到元素 k ,然后结果 k * 2 即可,和奇数的算法类似
  5. 最后不断递归只剩 1 个元素为止
class Solution {
    public int lastRemaining(int n) {
        return lH(n, true);
    }

    public int lH(int n, boolean right) {
        if (n <= 1) return n;
        if (!right && (n % 2) == 0) {
            return lH(n / 2, !right) * 2 - 1;
        }
        return lH(n / 2, !right) * 2;
    }
}

执行耗时:3 ms,击败了98.59% 的Java用户
内存消耗:37.3 MB,击败了60.73% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/111879997