The topics are as follows:
Problem- solving ideas: For this kind of number type of questions, the numbers generally have inherent rules. No matter how many times you operate, the array of this question is always an arithmetic sequence. From the sequence [1 2 3 4 5 6 7 8 9] -> [2 4 6 8] -> [2 6] -> [6], we can get the tolerances to be 1, 2, and 4, respectively. If we expand n a little and print out the remaining array sequence of each step, we can easily find that the tolerance is the power of pow(2,n). Next, we only need to record the low, high and the length of the remaining sequence after each operation, until the last sequence has only one element.
code show as below:
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