5.8
一个简单的二分查找而已。英语出题感觉高大上了不少呢。
/* 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
int low = 1;
int height = n;
return guessNumber1(low,height);
}
public int guessNumber1(int low,int height){
if(guess(low) == 0){
return low;
}
if(guess(height) == 0){
return height;
}
int mid = (low + height)/2;
if(guess(mid) == 0){
return mid;
}
if(guess(mid) < 0){
return guessNumber1(low,mid);
}
return guessNumber1(mid,height);
}
}