.
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;
}
}
}
}