题目:猜数字大小
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的数字,你猜哪个数字是我选择的数字。每次你猜错了,我会告诉你我选择的数字比你告诉我的数字大还是小。你调用guess(int num)接口可以返回三种可能的结果(-1,1,0)。-1代表我的数字小,1代表我的数字大,0代表你刚好猜中了。
最简单的方法就是采用二分查找法。
代码:C++版:0ms
// 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) { if (guess(n) == 0) return n; int left = 1, right = n; while (left < right) { int mid = left + (right - left)/2, res = guess(mid); if (res == 0) return mid; else if (res == 1) left = mid; else right = mid; } return left; } };