[leetcode] 374. Guess Number Higher or Lower

作者:luozhipeng   发表日期:2016-7-13  浏览:623次

 

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.


题意:给出一个数n和选中的一个数p, 1<= p<=n, 另外有个函数guess(int num),  每次我们都猜一个数,如果猜大了guess返回-1, 猜小了返回1, 猜对了返回0。问题就是使用这个函数最快速猜出p来。

 

输入:n, p

返回:猜对的p

 

思路:二分查找即可。

 


// 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 mid, left = 1, right = n;
        while(left <= right)
        {
            mid = left/2 + right/2 + (left&right&1);
            int flag = guess(mid);
            if(flag == 0)
                return mid;
            else if(flag == -1)
                right = mid - 1;
            else
                left = mid + 1;
        }
        
        return mid;
    }
};

标签:

本文固定链接: http://www.luozhipeng.com/?p=548
转载请注明: luozhipeng 2016-7-13 于 罗志鹏的BLOG 发表

上一篇: :下一篇
评论:请安装多说插件!
返回顶部