[leetcode]374. Guess Number Higher or Lower

来源:互联网 发布:车铣中心自动编程 编辑:程序博客网 时间:2024/05/16 11:13

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 (-11, 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.

My codes:

// Forward declaration of guess API.// @param num, your guess// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0int guess(int num);class Solution {public:    int guessNumber(int n) {        max=n;        min=0;                while(min<=max)        {            result=guess(min+(max-min)/2);            if(result==-1)                max=min+(max-min)/2-1;            if(result==1)                min=min+(max-min)/2+1;            if(result==0)                {                    max=min=min+(max-min)/2;                    break;                }        }        return max;    }private:    int max;    int min;    int result;};

Attention:

1.折半查找法,找分界线容易犯(max+min)/2的错误
2.重新对max和min进行赋值时,由于min+(max-min)/2已经进行判断,所以max=min+(max-min)/2-1,min=min+(max-min)/2+1,可以节省一部分的花销,同时可以解决输入n=1,I pick 1的情况。
0 0
原创粉丝点击