首页 > 学院 > 开发设计 > 正文

[leetcode]390. Elimination Game

2019-11-06 07:48:23
字体:
来源:转载
供稿:网友

题目链接: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;    }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表