笨方法,机智的解法是调换下标,有需要了解的可以搜索相关内容
原题见下图
小米面试题function xm2(n, bool = false) {
let puke = []
puke[0] = 0
puke[1] = [1]
puke[2] = [2, 1]
if (bool) {
puke[2] = [1, 2]
}
// puke[3] = [1, 3, 2, 4]
for(let j=3; j<=n; j=j+1) {
let rightTree = []
let leftTree = []
for(let i=0; i<Math.ceil(j/2); i++) {
rightTree.push(Math.floor(j/2)+1+i)
}
if (!bool) {
rightTree = rightTree.reverse()
}
leftTree = puke[Math.floor(j/2)].concat([])
puke[j] = new Array(j)
for(let m=0; m<j; m++){
if(m%2 == bool) {
puke[j][m] = rightTree.shift()
} else {
puke[j][m] = leftTree.shift()
}
}
}
return puke[n]
}
function c(n, bool){
console.log(xm2(n, bool))
}
网友评论