这道题目并没有什么特别可说的地方,看到题目的描述就可以明白这是一个需要使用Binary Search解决的问题,所以直接使用Binary Search即可,代码如下:
/* 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 left = 1;
int right = n;
// Binary search
while(left < right){
int mid = left + (right - left) / 2;
if(guess(mid) == -1) right = mid - 1; // guess number is higher, move to right
else if(guess(mid) == 1) left = mid + 1; // guess number is higher, move to left
else return mid; // correct
}
return left;
}
}
思考:
1. 虽然这道题目非常简单,但并不是说没有需要注意的问题,比如这道题目中Binary Search的模版写法一开始竟然有些生疏了,好久写不出来,这个问题要引起重视,对于基础的算法和数据结构应该多加练习
2. 明白Binary Search的一个性质,就是如果while(left < right)使用这种写法,那么如果Binary Search找不到目标的话,最终的结果是left = right
3. 对于搜索,查找类型的问题,一定要有使用Binary Search的敏感度