[leetcode]: 374. Guess Number Higher or Lower

来源:互联网 发布:淘宝店铺如何一件代发 编辑:程序博客网 时间:2024/06/06 01:20

1.题目

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):

给一个数n,系统随机选一个数x,1<=x<=n,要你猜出系统选中的数x是多少。
guess函数会给出提示。
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!

Example:
n = 10, I pick 6.
Return 6.

2.分析

二分查找

3.代码

int guess(int num);class Solution {public:    int guessNumber(int n) {        int start = 1;        int end = n;        while (start <= end) {            int mid = start + (end - start) / 2;            if (guess(mid) == 0)                return mid;            else if (guess(mid) == 1)                start = mid + 1;            else                end = mid - 1;        }    }};
原创粉丝点击