本章主要用两种方法实现递归与非递归
使用递归的话,可能会导致空间消耗要比非递归代码要大很多。
非递归
var guessNumber = function (n) {
let low = 1, high = n
while (low <= high) {
let mid = Math.floor((low + high) / 2)
const res = guess(mid)
if (res === 0) {
return mid
} else if (res === 1) {
low = mid + 1
} else {
high = mid - 1
}
}
};
递归
const rec = (low, high) => {
if (low > high) return;
const mid = Math.floor((low + high) / 2);
const res = guess(mid);
if (res === 0) {
return mid;
} else if (res === 1) {
return rec(mid + 1, high);
} else {
return rec(1, mid - 1);
}
};
return rec(1, n);