leetcode 390. Elimination Game

56 篇文章 0 订阅
53 篇文章 0 订阅

前言

这类题目纯粹属于观察规律的类型,在做这类题目的时候不要急于开始写代码,先找出规律,再动笔。

题目描述

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

解题思路

我们首先分析能够得到的信息。一个很容易观察到的变化规律就是步长信息,那我们就首先得到步长的规律。观察第一列的步长为2,第二列的步长为4(相隔元素),第三列元素为8(假设存在10 11 12 第二列元素就变成 2 4 6 8 10 12 第三列就变成 2 6 10),也就是说步数在每轮循环中是上一轮的两倍。我们再来观察元素个数递减规律,发现元素个数是按1/2的速度递减的。当递减元素个数减少到1时,就得到了最终的剩余元素。最难的部分就是追踪每次的头部元素,很容易观察到的一个结论是,从左侧开始的头部元素都是上一次的头部元素加上步长。对于从右侧开始的迭代过程,则分为两种情况,一种情况是左侧头部元素不变,一种情况是左侧头部元素为上次迭代的头部元素加步长,对于后一种情况,我们容易观察到的一点是,在剩余元素是奇数个时,头部元素会发生改变,否则不变。因此,根据上面分析得到的几点结论,我们可以写出最终的解如下:

class Solution {
public:
    int lastRemaining(int n) {
        auto remaining = n;
        auto head = 1;
        auto step = 1;
        auto isLeft = true;
        while(remaining>1) {

            if(isLeft||remaining&1==1) {
                head = head+step;
            }
            step*=2;
            remaining/=2;
            isLeft = !isLeft;
        }
        return head;
    }
};

后记

遇到这种题目,不要着急去写,先把能够得到的信息列出来,然后分析题目要求,再挖掘有用的信息,一步一步分析。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值