标签:lis 否则 etc ted nat from line ever tco
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
Leetcode 390. Elimination Game
标签:lis 否则 etc ted nat from line ever tco
原文地址:http://www.cnblogs.com/lettuan/p/6218999.html