首页 > 其他 > 详细

leetcode-374-Guess Number Higher or Lower(二分查找)

时间:2018-06-02 14:12:43      阅读:221      评论:0      收藏:0      [点我收藏+]

题目描述:

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.

 

要完成的函数:

int guess(int num);//api函数

int guessNumber(int n) 

 

说明:

1、给定一个整数 n,从1到n中挑一个数出来,让你猜是哪个数。每次你猜一个数,调用一次api函数,返回0就代表刚好是这个数,你猜对了!如果返回-1,就表示你猜的数太大了,实际的数比这个小。如果返回1,就表示你猜的数太小了,实际的数比这个大。要求最终返回对的那个数。

2、这道题很明显是一道二分查找的题目,手工写一个二分查找的代码。

代码如下:(附详解)

    int guess(int num);
    int guessNumber(int n) 
    {
        int low=1,high=n,mid,t;
        while(low<=high)
        {
            mid=low+(high-low)/2;//写成 mid=(low+high)/2 可能会上溢
            t=guess(mid);
            if(t==0)
                return mid;
            else if(t==-1)//实际的数比mid小
                high=mid-1;
            else          //实际的数比mid大
                low=mid+1;
        }
    }

上述代码实测2ms,beats 100.00% of cpp submissions。

leetcode-374-Guess Number Higher or Lower(二分查找)

原文:https://www.cnblogs.com/king-3/p/9125248.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!