题目:
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.
翻译:
我们在玩一个猜的游戏,游戏是如下这样的:
我从 1 到 n 中选择一个数字,你需要猜出我选择时哪一个数字。
每一次你猜错后,我都会告诉你猜的数字是高了还是低了。
你调用一个预定义的API guess(int num)
返回3个可能的结果(-1
, 1
,或 0
):
-1 : 我的数字要低一些 1 : 我的数字要高一些 0 : 祝贺你,你找到了!
例子:
n = 10, 我选择 6. 返回 6.
思路:
这道题就是一道二分查找的问题。之前也写过类似的题目。具体见代码。
C++代码(Visual Studio 2017):
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int low = 1;
int high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
if (guess(mid) == -1) {
high = mid - 1;
}
if (guess(mid) == 1) {
low = mid + 1;
}
if (guess(mid) == 0)
return mid;
}
}
};