一、题目
二、示例
输入:n = 10, pick = 6
输出:6
输入:n = 1, pick = 1
输出:1
输入:n = 2, pick = 1
输出:1
输入:n = 2, pick = 2
输出:2
三、思路
典型的二分查找
四、代码
/**
* Forward declaration of guess API.
* @param {number} num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* var guess = function(num) {}
*/
/**
* @param {number} n
* @return {number}
*/
var guessNumber = function(n) {
let left = 1
let right = n
let mid = Math.floor((left + right) / 2)
while(guess(mid) !== 0) {
if(guess(mid) === -1) {
right = mid -1
}else {
left = mid + 1
}
mid = Math.floor((left + right) / 2)
}
return mid
};
五、总结
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_47450807/article/details/123826270
内容来源于网络,如有侵权,请联系作者删除!