题目地址
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:
1 | Input: |
解题思路
题目要求按照给定的顺序多次删除数组内容:首先按照从左到右删除奇数索引上的数字,然后从右到左删除奇数索引上的数字。依次循环直到只剩一个数字然后返回这个数字。
以下这个霸气的解法不是我自己的(很惭愧智商不够),这个解法将题目分为镜像的子题目,使用递归求解。
After first elimination, all the numbers left are even numbers.
Divide by 2, we get a continuous new sequence from 1 to n / 2.
For this sequence we start from right to left as the first elimination.
Then the original result should be two times the mirroring result of lastRemaining(n / 2).
解题代码【.CPP】
1 | class Solution { |