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 will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.
Example 1:
Input: n = 10, pick = 6
Output: 6
现有1~n之间的一个数字,你要去猜是哪一个,每次可以通过guess(int num)函数来确定你猜的数字跟实际数字的大小。
从升序数组1~n中找到目标数字,很明显要用到binary search.
只不过每次和目标数字比大小不是直接比,而是通过函数int guess(int num),
通过它的返回值确认现在的mid和目标数字的大小关系。
public int guessNumber(int n) {
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) return mid;
if(guess(mid) < 0) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}