Guess Number Game We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked.Every time you guess wrong, I’ll tell you whether the number is higher or lower.You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
样例 n = 10, I pick 4 (but you don’t know) Return 4. Correct !
思路:一开始觉得这就是普通的二分查找问题,便写出如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* 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); */
publicclassSolutionextendsGuessGame{
/**
* @param n an integer
* @return the number you guess
**/
publicintguessNumber(int n){
// Write your code here
int left = 1;
int right = n;
while (left <= right) {
int mid = (right + left) /2;
int res = guess(mid);
if (res == 0) {
return mid;
}
if(res == -1) {
right = mid - 1;
}else {
left = mid + 1;
}
}
return -1;
}
}
结果在下列测试用例时发生错误:
1
2
3
4
5
6
7
8
9
输入
2147483647
2147483647
期望答案
2147483647
提示
Your code ran too much time than we expected. Check your time complexity. Time limit exceeded usually caused by infinite loop if your time complexity is the best.