Leetcode 390. Elimination Game
Posted lettuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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
解法一:关键在于维护一个boolean变量left2right来表明当前这一轮elimination是否为从左往右。另外,对于当前这一step来说,如果所剩的元素个数为奇数,那么头尾元素都会被去掉,否则的话头元素被去掉,但是尾元素不变。相邻元素的距离随着每一步都会放大两倍。
例如下图的两个case:
1 class Solution(object): 2 def lastRemaining(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 gap = 1 8 low, high = 1, n 9 left2right = True 10 while low < high: 11 n = (high - low)/gap 12 if left2right == True: 13 low += gap 14 if n%2 == 0: 15 high -= gap 16 else: 17 high -= gap 18 if n%2 == 0: 19 low += gap 20 gap *= 2 21 left2right = not left2right 22 return low 23
简化解法:其实并没有必要维护 low 和 high 两个边界变量。 while循环的终止条件可以用 gap*2 <= n。可以将left2right和right2left都写到一起,中间用L11判定一下是不是已经剩下最后一个元素了。L13里的 n//gap 不管n的奇偶性总能返回right2let的list长度。
1 class Solution(object): 2 def lastRemaining(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 gap = res = 1 8 while gap*2 <= n: 9 res += gap 10 gap *= 2 11 if gap*2 > n: 12 break 13 if (n//gap)%2 == 1: 14 res += gap 15 gap *= 2 16 return res
以上是关于Leetcode 390. Elimination Game的主要内容,如果未能解决你的问题,请参考以下文章