LeetCode每日一题: 猜数字大小(No.374)

栏目: 编程工具 · 发布时间: 6年前

我们正在玩一个猜数字游戏。 游戏规则如下:
我从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。
每次你猜错了,我会告诉你这个数字是大了还是小了。
你调用一个预先定义好的接口 guess(int num),它会返回 3 个可能的结果(-1,1 或 0):

-1 : 我的数字比较小
 1 : 我的数字比较大
 0 : 恭喜!你猜对了!
复制代码

示例:

输入: n = 10, pick = 6
输出: 6
复制代码

思考:

这题与二分查找类似,同样是二分查找方法,通过已有的guess接口来返回大小,大于中间数向右查找,小于中间数向左查找。
复制代码

实现:

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int low = 1;
        int high = n;
        int num = 0;
        while (low <= high) {
            num = low + (high - low) / 2;
            if (guess(num) == 0) {
                return num;
            } else if (guess(num) == -1) {
                high = num - 1;
            } else if (guess(num) == 1) {
                low = num + 1;
            }
        }
        return num;
    }
}复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Information

The Information

James Gleick / Vintage / 2012-3-6 / USD 16.95

James Gleick, the author of the best sellers Chaos and Genius, now brings us a work just as astonishing and masterly: a revelatory chronicle and meditation that shows how information has become th......一起来看看 《The Information》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码