Leetcode刷题(第374题)——猜数字大小

x33g5p2x  于2022-03-31 转载在 其他  
字(0.5k)|赞(0)|评价(0)|浏览(338)

一、题目

二、示例

输入: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
};

五、总结

相关文章