390. Elimination Game

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 9
2 4 6 8
2 6
6

Output:
6

一刷
题解:
给出1...n这n个数字。
首先从左到右,每隔一个删除一个。然后从右到左,每隔一个删除一个。重复这个过程。返回最后留下的一个元素。
我们用head表示head现在指向的元素,一次iter之后,(假装移除),那么step会变成之前的两倍。根据这规律保存head, head为最后留存的元素。
如果是从左到右,head += step;
如果是从右到左,且size为奇数(为偶数head不变),head+=step;(head被删除)

class Solution {
    public int lastRemaining(int n) {
        boolean left = true;
        int remaining = n;
        int step = 1;
        int head = 1;
        while(remaining>1){
            if(left || remaining%2 == 1){
                head = head + step;
            }
            remaining /= 2;
            step = step*2;
            left = !left;
        }
        return head;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,767评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,797评论 0 23
  • 【抵巇第四】 原文(4.3)天下纷错,士无明主,公侯无道德,则小人馋贼,贤人不用。圣人窜匿,贪利诈伪者作。君臣相惑...
    马新阅读 892评论 0 51
  • 苏州客 我叫齐小美,报社编辑。男友李强,开了一家家居床品店。 恋爱一年半,感情稳定。决定...
    苏州客阅读 364评论 3 3
  • 六月的心陌,总有三两朵娉婷悄然开放;总有一些人让我终生难忘。 从去年秋高气爽的九月到今年火伞高...
    晶兮阅读 1,109评论 12 14