LeetCode—猜数字大小(二分)

猜数字大小(简单)

2020年6月23日

题目来源:力扣

在这里插入图片描述

解题

看题目就是一道普通的二分题了。

这里取中间数,我一开始用(l+r)/2超时了,想想应该是数据量过大可能导致整型溢出,后面改成了l+(r-l)/2。

/** 
 * Forward declaration of guess API.
 * @param  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
 * int guess(int num);
 */

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int l=1;
        int r=n;
        while(l<=r){
            int c=l+(r-l)/2;
            int num=guess(c);
            if(num==0) return c;
            else if(num==-1) r=c-1;
            else l=c+1;
        }
        return -1;
    }
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章