My code:
/* 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 begin = 1;
int end = n;
while (begin <= end) {
int mid = begin + (end - begin) / 2;
if (guess(mid) < 0) {
end = mid - 1;
}
else if (guess(mid) > 0) {
begin = mid + 1;
}
else {
return mid;
}
}
return -1;
}
}
简单题。
可以看下他给的一篇文章,介绍了一个新的search
叫做: Ternary Search
reference:
https://leetcode.com/articles/guess-number-higher-or-lower/#approach-3-ternary-search-accepted
Anyway, Good luck, Richardo! — 09/21/2016