We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I’ll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!Example:
n = 10, I pick 6.
Return 6.
一开始理解错题意了答错了好几次,正如讨论区一个帖子所说:
the key point is to read the problem carefully
注意,判断大小时是基于 pick number 判断。因为是反复比较大小,所以可以联想到二分法。但是要注意到常规二分法如:mid = (low + high) / 2,有可能在计算最大数和最小数相加时出现溢出,所以 mid 的求法要改变一下。代码如下:
public class Solution extends GuessGame {
public int guessNumber(int n) {
int low = 1;
int high = n;
int mid;
while(high >= low) {
mid = low + (high - low) / 2; //注意 mid 求法,其实就是 low / 2 + high / 2
int g = guess(mid);
if(g == 0) return mid;
if(g == 1) low = mid + 1;
else high = mid;
}
return n;
}
}