其他分享
首页 > 其他分享> > LeetCode -- 374. 猜数字大小

LeetCode -- 374. 猜数字大小

作者:互联网

/**
 * 374. 猜数字大小
 *
 * 经典二分查找题目,不解释
 * 唯一注意点:
 * 注意 middle = left + (right - left) / 2;
 * 其中 left + (right - left) 这样写是为了防止溢出错误
 * 
 */
public class Solution374 {
    int pack  = 89890;
    public int guessNumber(int n) {
        int left = 1, right = n;
        int res = n;
        while (left <= right) {
            int middle = left + (right - left) / 2;
            if (guess(middle) == 0) {
                res = middle;
                break;
            } else if (guess(middle) < 0) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        return res;
    }
}

标签:guess,right,--,res,374,middle,int,LeetCode,left
来源: https://blog.csdn.net/qq_39611310/article/details/117906993