374. 猜数字大小
题目:
思路:
【1】里面自带了个判断函数,所以只要把选中的值塞进去判断即可。
代码展示:
//时间0 ms 击败 100% //内存38 MB 击败 78.84% /** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number * 1 if num is lower than the picked number * otherwise return 0 * int guess(int num); */ public class Solution extends GuessGame { public int guessNumber(int n) { // 因为是要从[1-n]中猜 int left = 1, right = n; while (left < right) { // 循环直至区间左右端点相同 //先取中位进行猜 int mid = left + (right - left) / 2; // 防止计算时溢出 // int res = guess(mid); if (res == 0){ return mid; }else if (res < 0) { right = mid - 1; // 答案在区间 [left, mid-1] 中 } else { left = mid + 1; // 答案在区间 [mid+1, right] 中 } } // 此时有 left == right,区间缩为一个点,即为答案 return left; } }