LeetCode 390. Elimination Game

如果用模拟做,需要频繁移动数组元素,导致效率很低。实际上,我们并不需要知道当前数组每个元素是什么,因为每次间隔删除元素的性质,我们可以计算出每轮过后相邻元素间隔是多少。一开始相距1,每轮过后间隔都会翻倍。由此,我们只要知道第一个元素的正确位置和还剩余多少元素,就可以知道剩余的所有元素。

需要注意的时,-> 删除时,第一个元素一定会被删除,所以 head += step 得到新的第一个元素。

但是 <- 删除时,只有在当前剩余元素是奇数个时,第一个元素才会被删除,需要更新第一个元素的位置。

如 比如 123456 -> 246 -> 4,第二轮2会被删除,head指向4。

class Solution {
public:
    int lastRemaining(int n) {
        int head=1, step=1;
        bool direction=true; // true for ->, false for <-
        while (n>1){
            if (direction) head += step;
            else head += (n%2==0)?0:step;
            step *= 2;
            n /= 2;
            direction = !direction;
        }
        return head;
    }
};

时间复杂度 O(logn)

 

Reference

https://leetcode.com/problems/elimination-game/discuss/355060/C++-simple-explanation-with-pictures

posted @ 2019-09-23 01:57  約束の空  阅读(112)  评论(0编辑  收藏  举报