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.
下面给出自己的迭代求解算法:
var last = function(n,lORr){
if(n==1){
return 1
}else{
if(lORr){//from left to right
if(n%2 === 0){
return 2*last((n/2),false)
}else{
return last(n-1,true)
}
}else{//from right to left
if(n%2 === 0){
return 2*last((n/2),true)-1
}else{
return 2*last(((n-1)/2),true)
}
}
}
}
代码分析:
本题从正向来做,看似可行,实则没有多大意义,浪费时间跟内存消耗。仔细分析题意可以发现并不需要正向解决问题。逆向考虑,也许会更方便。每次排除一半,最后只留下一个数。逆推过来的话,就是:第一个数,反推倒数第二步剩下的三个数(或两个数)。每次删除的数总会呈对称结构,删除的总次数不会多于Log2N次。
从解题的复杂性来看,用递归迭代是一个不错的方法。

本文探讨了一种筛选算法,该算法从一个有序整数列表开始,通过交替地从左到右和从右到左移除元素的方式,最终只剩下一个数字。文章提供了一个递归迭代的解决方案,并对其进行了详细解析。
890

被折叠的 条评论
为什么被折叠?



