我们正在玩一个猜数字游戏。 游戏规则如下:
我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。
每次你猜错了,我会告诉你这个数字是大了还是小了。
你调用一个预先定义好的接口 guess(int num),它会返回 3 个可能的结果(-1,1 或 0):
-1 : 我的数字比较小
1 : 我的数字比较大
0 : 恭喜!你猜对了!
示例 :
输入: n = 10, pick = 6
输出: 6
方法一:二分查找
/* 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 {
public int guessNumber(int n) {
int L = 1, R = n;
while(L <= R){
int mid = L + (R - L) / 2;
if(guess(mid) == 0){
return mid;
}
else if(guess(mid) == -1){
R = mid - 1;
}
else{
L = mid + 1;
}
}
return 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 {
public int guessNumber(int n) {
int L = 1, R = n;
while(L <= R){
int mid1 = L + (R - L) / 3;
int mid2 = R - (R - L) / 3;
int res1 = guess(mid1);
int res2 = guess(mid2);
if(res1 == 0){
return mid1;
}
if(res2 == 0){
return mid2;
}
else if(res1 == -1){
R = mid1 - 1;
}
else if(res2 == 1){
L = mid2 + 1;
}
else{
L = mid1 + 1;
R = mid2 - 1;
}
}
return 0;
}
}