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






0 0
原创粉丝点击