gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-13 03:09:35 26 4
gpt4 key购买 nike

一、题目

二、示例

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

五、总结

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com