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
):
-1 : My number is lower 1 : My number is higher 0 : Congrats! You got it!
Example:
n = 10, I pick 6. Return 6.
Subscribe to see which companies asked this question
这个题很好玩!代码写的比较顺利,思路一上来也比较对。但是却在一个小问题上翻了船。、
/* 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;
if(guess(n) == 0)
return n;
while(left<right){
<h3> <u> int num = left+(right-left)/2;</u></h3> int t = guess(num);
if(t == 0)
return num;
else if(t == 1)
left = num;
else
right = num;
}
return left;
}
}
重点看我高亮放大的部分:int num = left + (right-left)/2;
我一开始写的是 num = (left+right)/2;
但是运行时在这个例子上超时。
2126753390
1702766719
原因时,两个数字相加之后,就超过了界限。但是如果用left+ (right-left)/2的话则不会过界,好玩吧,嘿嘿嘿,新大陆。