Leetcode 390:消除游戏

题目描述

给定一个从1 到 n 排序的整数列表。
首先,从左到右,从第一个数字开始,每隔一个数字进行删除,直到列表的末尾。
第二步,在剩下的数字中,从右到左,从倒数第一个数字开始,每隔一个数字进行删除,直到列表开头。
我们不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。
返回长度为 n 的列表中,最后剩下的数字。

示例:

输入:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6

输出:
6

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/elimination-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

朴素的思路(超时)

class Solution {
public:
    int lastRemaining(int n) {
        vector<int> vect;
        for(int i=0;i<n;++i) vect.push_back(i+1);
        while(vect.size()>1){
            int del=1;
            auto it=vect.begin();
            while(it!=vect.end()){
                if(del==1){
                    del=0;
                    it=vect.erase(it);
                }else{
                    del=1;
                    it++;
                }
            }
            reverse(vect.begin(),vect.end());
        }
        return vect[0];
    }
};

数学

class Solution {
public:
    int lastRemaining(int n) {
        int start=1,step=1;
        bool isNormal=true;
        while(n>1){
            if(isNormal) start+=step;
            else start=(n%2==0)?start:start+step;
            step*=2;
            n/=2;
            isNormal=!isNormal;
        }
        return start;
    }
};
发布了584 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_35338624/article/details/104082003