zoukankan      html  css  js  c++  java
  • 【leetcode】390. Elimination Game

    题目如下:

    解题思路:对于这种数字类型的题目,数字一般都会有内在的规律。不管怎么操作了多少次,本题的数组一直是一个等差数列。从[1 2 3 4 5 6 7 8 9] -> [2 4 6 8] -> [2 6] -> [6]这个序列中,我们可以得到公差分别是1,2,4。如果我们把n扩大一点,打印出其中每一步剩余的数组序列,我们很容易发现公差是pow(2,n)次方,发现了这个规律后,一切就水到渠成了。接下来,我们只要记录每一次操作后剩下序列的low,high以及序列的长度,直到最后序列只有一个元素即可。

    代码如下:

    class Solution(object):
        def lastRemaining(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n == 1:
                return 1
            times = 1
            low = high = None
            length = n
            multiple = None
            while True:
                if times == 1:
                    length = length / 2
                    low = 2
                    if n % 2 == 0:
                        high = n
                    else:
                        high = n -1
                    multiple = pow(2, times)
                elif times % 2 == 0:
                    length = length / 2
                    high -= multiple
                    multiple = pow(2, times)
                    low = high - multiple*(length-1)
                else:
                    length = length / 2
                    low += multiple
                    multiple = pow(2, times)
                    high = low + multiple * (length - 1)
                times += 1
                if low >= high:
                    return high
            
  • 相关阅读:
    Linux 的grep命令显示日志文件指定前后行信息
    Windows下安装MySQL详细教程
    Maven安装配置(Windows10)
    Windows下配置Tomcat服务器
    java环境变量 的配置与详解
    工具使用篇-索引
    Fiddler抓包工具总结
    使用fiddler实现手机抓包
    网络安全-索引
    网络嗅探技术浅析
  • 原文地址:https://www.cnblogs.com/seyjs/p/8934453.html
Copyright © 2011-2022 走看看