问题描述:
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 3 possible results:
-1: The number I picked is lower than your guess (i.e. pick < num).
1: The number I picked is higher than your guess (i.e. pick > num).
0: The number I picked is equal to your guess (i.e. pick == num).
Return the number that I picked.
猜数字,游戏者每猜一个数字后得到反馈:大了,小了,对了。直到锁定最后的数字
思路:二叉搜索,没有疑问
代码如下:
public class Solution extends GuessGame {
public int guessNumber(int n) {
int left=1;
int right=n;
while(left<=right){
int mid=left+(right-left)/2;
int myGuess=guess(mid);
if(myGuess==0){
return mid;
}
else if(myGuess==-1){
right=mid;
}
else{
left=mid+1;
}
}
return -1;
}
}
时间复杂度:O(logn)