[leetcode]390. Elimination Game
来源:互联网 发布:淘宝怎么认证实名认证 编辑:程序博客网 时间:2024/06/05 03:25
题目链接:https://leetcode.com/problems/elimination-game/?tab=Description
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 92 4 6 82 66Output:6
class Solution{public: int lastRemaining(int n) { return l(n); } int l(int n) // from left to right { if(n==1) return 1; else if(n==2) return 2; else if((n&1)==1) return 2*r((n-1)/2); else return 2*r(n/2); } int r(int n) //from right to left { if(n==1) return 1; else if(n==2) return 1; else if((n&1)==1) return 2*l((n-1)/2); else return 2*l(n/2)-1; }};
思路:
第一次从左向右检索完,剩下,2 4 6 8, 其实这跟1 2 3 4的信息几乎是一样的,只是差了倍数2,所以问题就变为从右往左对规模4的问题进行操作,找到答案乘以2就行。对于从右往左,如果是1 2 3 4 5的话,检索完还剩2 4,同样是1 2的问题,如果是 1 2 3 4,剩 1 3,我们可以认为1是 2乘以2减一,总之,我们可以找到将每次的剩余子序列转化为同类子问题的方法。
需要讨论的有,每次开始的子问题是奇数还是偶数,决定下一次子问题的规模,然后这次的子问题和下次的子问题是什么递推关系。
- [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
- MySQL数据库——初涉'存储过程'基本操作(无参,IN,OUT)与变量术语基础概念
- 转贪心算法
- Python实现神经网络Part 1: 实现forward和BP算法的神经元
- linux(ubuntu)开放postgresql远程访问
- 最大连续数列的和
- [leetcode]390. Elimination Game
- maven打包,实现将jar包中的路径,打到对应的目录下
- 控制台程序,输入退格键不回显的方法
- 论持久战之Java性能监控工具(jmap)
- springboot+mybatis入门
- 十大排序算法 JAVA代码
- 分治算法(三)215. Kth Largest Element in an Array【middle】03-04
- 团结就是力量
- AlertDialog