390. Elimination Game
来源:互联网 发布:mysql原理 编辑:程序博客网 时间:2024/06/05 11:32
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
递归方法:
第一次从左向右检索完,剩下,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减一,总之,我们可以找到将每次的剩余子序列转化为同类子问题的方法。
public class Solution { public int lastRemaining(int n) { return left(n); } public int left(int n){ if(n==1) return 1; if(n==2) return 2; if(n%2!=0){ return 2*right((n-1)/2); } else{ return 2*right(n/2); } } public int right(int n){ if(n==1||n==2) return 1; if(n%2!=0){ return 2*left((n-1)/2); } else{ return 2*left(n/2)-1; } }}
数学推导:
http://www.cnblogs.com/dongling/p/5823911.html- 390. Elimination Game
- [LeetCode] 390. Elimination Game
- 390. Elimination Game
- 390. Elimination Game
- LeetCode 390. Elimination Game
- 390. Elimination Game
- 【LeetCode】390. Elimination Game
- 390. Elimination Game
- 【LeetCode】 390. Elimination Game
- 390. Elimination Game
- 390. Elimination Game
- LeetCode 390. Elimination Game
- [leetcode]390. Elimination Game
- 390. Elimination Game
- [LeetCode]390. Elimination Game
- LeetCode 390. Elimination Game
- [leetcode] 390. Elimination Game
- 390. Elimination Game
- 带新手走进神秘的HTTP协议
- APK瘦身从11M到7.8M
- [斐波那契博弈] BZOJ 2275 [Coci2010]HRPA & HDU 2516 取石子游戏
- leetcode刷题请单
- 2017年2月17日
- 390. Elimination Game
- POJ2991-Crane-线段树+计算几何
- JAVA排序方法
- [最小环 最小环计数 最大平均环 模板题] POJ 1734 Sightseeing trip & FZU 2090 旅行社的烦恼 & POJ 2949 Word Rings
- HDU2612 Find a way
- Java中的标识符和关键字
- 二分查找Binary Search
- Bzoj 1251: 序列终结者(splay)
- 前端关于屏幕的不同属性