原文地址:http://www.javashuo.com/article/p-nrzzjuib-bz.html html
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.this
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.spa
We keep repeating the steps again, alternating left to right and right to left, until a single number remains.code
Find the last number that remains starting with a list of length n.htm
Example:blog
Input: n = 9, 1 2 3 4 5 6 7 8 9 2 4 6 8 2 6 6 Output: 6
給定一個從1 到 n 排序的整數列表。
首先,從左到右,從第一個數字開始,每隔一個數字進行刪除,直到列表的末尾。
第二步,在剩下的數字中,從右到左,從倒數第一個數字開始,每隔一個數字進行刪除,直到列表開頭。
咱們不斷重複這兩步,從左到右和從右到左交替進行,直到只剩下一個數字。
返回長度爲 n 的列表中,最後剩下的數字。排序
示例:遊戲
輸入: n = 9, 1 2 3 4 5 6 7 8 9 2 4 6 8 2 6 6 輸出: 6
20ms
1 class Solution { 2 func lastRemaining(_ n: Int) -> Int { 3 return n == 1 ? 1 : 2 * (n / 2 + 1 - lastRemaining(n / 2)) 4 } 5 }
28msrem
1 class Solution { 2 func clear(lun: Int, lunCount: Int, lastNum: Int, n: Int) -> Int { 3 let lastSpan = (1<<(lun - 1)) 4 var tmpLastNum = lastNum 5 6 if lun % 2 == 0 || (n / lastSpan) % 2 != 0 { 7 tmpLastNum = tmpLastNum - lastSpan 8 } 9 10 if lun == lunCount { return tmpLastNum } 11 return clear(lun: lun + 1, 12 lunCount: lunCount, 13 lastNum: tmpLastNum, 14 n: n) 15 } 16 17 func lastRemaining(_ n: Int) -> Int { 18 if n == 1 { return 1 } 19 var lunCount = 0 20 var total = n 21 while total != 1 { 22 total = total / 2 23 lunCount += 1 24 } 25 return clear(lun: 1, 26 lunCount: lunCount, 27 lastNum: n, 28 n: n) 29 } 30 }