#374. 猜数字大小
难度:简单 考察:二分查找
题目描述
解题思路
题目有点说的不清楚,总之:
guess返回-1,如果猜的数字比实际选择的数字大
1,如果猜的数字比实际选择的大
1、二分递归
public int guessNumber(int n) {
return guessBinary(1,n);
}
public int guessBinary(int low,int high){
int mid = low + (high - low)/2;
if(guess(mid) == -1){
return guessBinary(low,mid-1);
}
else if(guess(mid) == 1){
return guessBinary(mid+1,high);
}
else
return mid;
}
2、不用递归,普通二分查找
public int guessNumber(int n) {
int low = 1,high = n;
while(low <= high) {
int mid = low + (high - low)/2;
if(guess(mid) == -1)
high = mid - 1;
else if (guess(mid) == 1) {
low = mid + 1;
}
else {
return mid;
}
}
return n;
}