[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减一,总之,我们可以找到将每次的剩余子序列转化为同类子问题的方法。

需要讨论的有,每次开始的子问题是奇数还是偶数,决定下一次子问题的规模,然后这次的子问题和下次的子问题是什么递推关系。

0 0
原创粉丝点击