【leetcode】390. Elimination Game

 2023-09-13 阅读 28 评论 0

摘要:题目如下: leetcode all in one。解题思路:对于这种数字类型的题目,数字一般都会有内在的规律。不管怎么操作了多少次,本题的数组一直是一个等差数列。从[1 2 3 4 5 6 7 8 9] -> [2 4 6 8] -> [2 6] -> [6]这个序列中,我们可以得

题目如下:

leetcode all in one。解题思路:对于这种数字类型的题目,数字一般都会有内在的规律。不管怎么操作了多少次,本题的数组一直是一个等差数列。从[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 1times = 1low = high = Nonelength = nmultiple = Nonewhile True:if times == 1:length = length / 2low = 2if n % 2 == 0:high = nelse:high = n -1multiple = pow(2, times)elif times % 2 == 0:length = length / 2high -= multiplemultiple = pow(2, times)low = high - multiple*(length-1)else:length = length / 2low += multiplemultiple = pow(2, times)high = low + multiple * (length - 1)times += 1if low >= high:return high

 

leetCode、转载于:https://www.cnblogs.com/seyjs/p/8934453.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/54247.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息