Skip to content

Latest commit

 

History

History
60 lines (49 loc) · 1.58 KB

374.md

File metadata and controls

60 lines (49 loc) · 1.58 KB

✏️基础刷题之( 374. Guess Number Higher or Lower)


. 2020-05-13 星期二 开始吧 库里的深夜食堂

✏️描述

一个猜大小的游戏,猜一个1-n之间的数,从接口获取接口,如果是0说明你猜对了返回结果,如果返回-1,太大了,如果返回1,太小了


✏️题目实例


✏️题目分析

典型的二分查找,对于二分查找,可以通过目录:算法获取有关知识

✏️最终实现代码

/** 
 * The API guess is defined in the parent class.
 * @param  num   your guess
 * @return 	     -1 if num is lower than the guess number
 *			      1 if num is higher than the guess number
 *               otherwise return 0
 * public function guess($num){}
 */

class Solution extends GuessGame {
    /**
     * @param  Integer  $n
     * @return Integer
     */
    function guessNumber($n) {
        $left=1;
        $right=$n;
        while($left<=$right){
            $middle=$left+(($right-$left)>>1);
            $res=$this->guess($middle);
            if($res===0){
                return $middle;
            }else if ($res===-1){
                $right=$middle-1;
            }else{
                $left=$middle+1;
            }
        }
    }
}

联系