今天和大家聊的问题叫做 消除游戏,我们先来看题面:https://leetcode-cn.com/problems/elimination-game/
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:
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 rightmost number and every other number from the remaining numbers.Keep repeating the steps again, alternating left to right and right to left, until a single number remains.Given the integer n, return the last number that remains in arr.
给定一个从1 到 n 排序的整数列表。首先,从左到右,从第一个数字开始,每隔一个数字进行删除,直到列表的末尾。第二步,在剩下的数字中,从右到左,从倒数第一个数字开始,每隔一个数字进行删除,直到列表开头。我们不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。返回长度为 n 的列表中,最后剩下的数字。
示例
输入: n = 9, 1 2 3 4 5 6 7 8 9 2 4 6 8 2 6 6 输出: 6
解题
class Solution { public: int lastRemaining(int n) { if(n == 1) return 1; return 2*(n/2)+2 - 2*lastRemaining(n/2); } };
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。