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 will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num)
, which returns 3 possible results:
-1
: The number I picked is lower than your guess (i.e.pick < num
).1
: The number I picked is higher than your guess (i.e.pick > num
).0
: The number I picked is equal to your guess (i.e.pick == num
).
Return the number that I picked.
Example 1:
Input: n = 10, pick = 6 Output: 6
Example 2:
Input: n = 1, pick = 1 Output: 1
Example 3:
Input: n = 2, pick = 1 Output: 1
Example 4:
Input: n = 2, pick = 2 Output: 2
Constraints:
1 <= n <= 231 - 1
1 <= pick <= n
猜数字大小。
猜数字游戏的规则如下:
每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。
你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或 0):-1:我选出的数字比你猜的数字小 pick < num
1:我选出的数字比你猜的数字大 pick > num
0:我选出的数字和你猜的数字一样。恭喜!你猜对了!pick == num
返回我选出的数字。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/guess-number-higher-or-lower
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这也是一个通过二分法调用API猜数字大小的题目。注意判断的边界是从1到N。
时间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 // start + 1 < end 11 // 举例,start - 0, end = 3 12 // 中间隔了起码有start + 1和start + 2两个下标 13 // 这样跳出while循环的时候,end < start 14 // 才有了最后的两个判断 15 while (start + 1 < end) { 16 int mid = start + (end - start) / 2; 17 if (guess(mid) == 0) { 18 return mid; 19 } else if (guess(mid) == 1) { 20 start = mid; 21 } else { 22 end = mid; 23 } 24 } 25 26 if (guess(start) == 0) { 27 return start; 28 } else { 29 return end; 30 } 31 } 32 }
另一种二分模板的写法,注意while的条件和start, end指针的变化。
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 <= 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 + 1; 16 } else { 17 end = mid - 1; 18 } 19 } 20 return start; 21 } 22 }