一、题目
二、代码
这个题目比较难理解,总之要使用预定的接口,pick是内定的目标数。
使用二分方法策略猜数字,注意边界。
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* int guess(int num);
*/
public class Solution extends GuessGame {
public int guessNumber(int n) {
int low = 1;
int high = n;
int mid = 0;
while(low <= high){
mid = (high - low) / 2 + low;
if(guess(mid) == 0){
return mid;
}else if(guess(mid) == -1){
high = mid - 1;
}else{
low = mid + 1;
}
}
return 0;
}
}