这也是一个通过二分法调用API猜数字大小的题目。注意判断的边界是从1到N。这题没有提供JavaScript的API所以我就直接上Java的代码了。
时间O(logn)
空间O(1)
1 /* The guess API is defined in the parent class GuessGame. 2 @param num, your guess 3 @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 int guess(int num); */ 5 6 public class Solution extends GuessGame { 7 public int guessNumber(int n) { 8 int start = 1; 9 int end = n; 10 while (start + 1 < end) { 11 int mid = start + (end - start) / 2; 12 if (guess(mid) == 0) { 13 return mid; 14 } else if (guess(mid) == 1) { 15 start = mid; 16 } else { 17 end = mid; 18 } 19 } 20 if (guess(start) == 0) return start; 21 return end; 22 } 23 }