LeetCode 390. Elimination Game
来源:互联网 发布:帝霸传奇手游源码 编辑:程序博客网 时间:2024/06/04 19:12
题目
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.
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 92 4 6 82 66Output:6
思路
递归,eg, n = 6: 1 2 3 4 5 6 如果从左往右,第一遍从左往右,删掉奇数,剩下偶数2 4 6,则将他们除以2,得到 1 2 3,即1~n/2的子序列,递归的下一步可对该子序列处理,不过是从右往左删除,最后剩下2,其实是原数列的4(乘以了2),所以递归形式为2 * helpler(n / 2, false);
若当前递归是从右往左,则要考虑n的奇偶,
eg. n为奇数,假设已除以了2,得到1 2 3 4 5 的子序列,当前递归状态是 n = 5 从右往左删除,得到 2 4,同理,也可把他们映射为 1 2,下一次递归则是从左往右处理,最终得到2,其实是原数列的4,所以需要乘以2的数;
eg. n为偶数,假设已除以了2,得到1 2 3 4 5 6 的子序列,当前递归状态是 n = 6 从右往左删除,得到 1 3 5,同理,也可把他们映射为 1 2 3,下一次递归则是从左往右处理,最终得到2,其实是原数列的3,所以需要乘以2再减1得到原序列的数;
所以,若当前递归是从右往左,当前n为偶数时,结果要乘以2再减1;n为奇数时,只需要乘以2,所以递归形式为2 * helpler(n / 2, true) - 1 + n % 2;
代码
class Solution {public: int helpler(int n, bool left){ if(n == 1) return 1; if(left == true) return 2 * helpler(n / 2, false); else return 2 * helpler(n / 2, true) - 1 + n % 2; } int lastRemaining(int n) { return helpler(n, left); }};
- [LeetCode] 390. Elimination Game
- LeetCode 390. Elimination Game
- 【LeetCode】390. Elimination Game
- 【LeetCode】 390. Elimination Game
- LeetCode 390. Elimination Game
- [leetcode]390. Elimination Game
- [LeetCode]390. Elimination Game
- LeetCode 390. Elimination Game
- [leetcode] 390. Elimination Game
- leetcode 390. Elimination Game
- leetcode 390. Elimination Game
- Leetcode 390. Elimination Game
- LeetCode—390. Elimination Game
- [Leetcode] 390. Elimination Game 解题报告
- leetcode 390. Elimination Game 消除游戏
- 390. Elimination Game
- 390. Elimination Game
- 390. Elimination Game
- (2)---------->产品经理
- RxJava的使用
- rdt2.1与rdt2.2
- mysql基本语句
- EXCEL中合并同列中连续相同内容的单元格
- LeetCode 390. Elimination Game
- Check process case
- CUDA+VS2013+Windows7环境配置
- 论文中图片格式的微调使得满页
- 微信小程序源码汇总
- HTML+CSS:圆形和圆角图片格式
- task_struct结构注释
- (四)CentOS 7安装Nginx(编译安装)
- (不推荐使用)springMVC基本配置+继承MultiActionController来实现根据参数名指定要请求的方法