描述:
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):
样例;
n = 10, I pick 4 (but you don't know)
Return 4. Correct !
思路:
采用二分法即可,注意判断是否 n == target => guess(n) == 0 以避免超时。
/* The guess API is defined in the parent class GuessGame.
@param num, your guess
@return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num); */
public class Solution extends GuessGame {
/**
* @param n an integer
* @return the number you guess
*/
public int guessNumber(int n) {
// Write your code here
if(guess(n) == 0){
return n;
}
int low = 1;
int high = n;
while(low < high){
int mid = low + (high - low)/2;
int record = guess(mid);
if(record == 0){
return mid;
}else if(record == 1){
low = mid;
}else if(record == -1){
high = mid;
}
}
return low;
}
}