File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other
3+ number afterward until you reach the end of the list.
4+
5+ Repeat the previous step again, but this time from right to left, remove the right most number and every other number
6+ from the remaining numbers.
7+
8+ We keep repeating the steps again, alternating left to right and right to left, until a single number remains.
9+
10+ Find the last number that remains starting with a list of length n.
11+
12+ Example:
13+
14+ Input:
15+ n = 9,
16+ 1 2 3 4 5 6 7 8 9
17+ 2 4 6 8
18+ 2 6
19+ 6
20+
21+ Output:
22+ 6
23+ """
24+ __author__ = 'Daniel'
25+
26+
27+ class Solution (object ):
28+ def lastRemaining (self , n ):
29+ """
30+ Brute force O(n): A = A[::2][::-1]
31+
32+ Simulate the game and find pattern of head/first element: O(lg n)
33+ :type n: int
34+ :rtype: int
35+ """
36+ remain = n
37+ head = 1
38+ step = 1
39+ from_left = True
40+ while remain > 1 :
41+ if from_left :
42+ head += step
43+ elif remain % 2 == 1 :
44+ head += step
45+
46+ step *= 2
47+ remain /= 2
48+ from_left = not from_left
49+
50+ return head
You can’t perform that action at this time.
0 commit comments