0
点赞
收藏
分享

微信扫一扫

LeetCode 374. 猜数字大小

四月Ren间 2022-05-02 阅读 54

题目链接:

力扣icon-default.png?t=M3K6https://leetcode-cn.com/problems/guess-number-higher-or-lower/

【分析】二分查找的应用,直接套模板改一下区间判定的条件即可,需要注意求mid的时候可能溢出int的范围。

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int mid, left = 1, right = n;
        while(left <= right){
            mid = (int)((left + (long)right) / 2);
            int ret = guess(mid);
            if(ret == 0) return mid;
            else if(ret == -1) right = mid - 1;
            else left = mid + 1;
        }
        return -1;
    }
}

 

举报

相关推荐

0 条评论