博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
每天一道LeetCode--374. Guess Number Higher or Lower
阅读量:6147 次
发布时间:2019-06-21

本文共 1279 字,大约阅读时间需要 4 分钟。

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.

解法一:  递归

public int guessNumber(int n) {        return guessNumber(1, n);    }    /*递归*/    private  int guessNumber(int start,int end){        int mid=start+(end-start)/2;        if(guess(mid)==-1){            return guessNumber(start,mid-1);        }else        if(guess(mid)==1){            return guessNumber(mid+1,end);        }else{            return mid;        }    }}

解法二:循环

public int guessNumber(int n) {                int low = 1;        int high = n;               while (low <= high) {            int mid = low+(high-low)/2;            int guessResult = guess(mid);            if (guessResult == 0)                return mid;            if (guessResult == 1)                low = mid+1;            else if (guessResult == -1)                 high = mid-1;        }                return -1;    }

其他解法,参考:

转载于:https://www.cnblogs.com/xiaoduc-org/p/6106033.html

你可能感兴趣的文章
HTML.2文本
查看>>
Ubuntu unity安装Indicator-Multiload
查看>>
解决Eclipse中新建jsp文件ISO8859-1 编码问题
查看>>
7.对象创建型模式-总结
查看>>
1、块:ion-item
查看>>
【论文阅读】Classification of breast cancer histology images using transfer learning
查看>>
移动端处理图片懒加载
查看>>
jQuery.on() 函数详解
查看>>
谈缓存和Redis
查看>>
【转】百度地图api,根据多点注标坐标范围计算地图缩放级别zoom自适应地图
查看>>
用户调研(补)
查看>>
ExtJS之开篇:我来了
查看>>
☆1018
查看>>
oracle 去掉空格
查看>>
6.13心得
查看>>
Runtime类
查看>>
eclipse decompiler
查看>>
记一个搜索网盘资源的网站
查看>>
jdk1.7和jdk1.8的String的getByte方法的差异
查看>>
java父子进程通信
查看>>