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;
    }
}复制代码

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

查看所有标签

猜你喜欢:

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

Mastering Bitcoin

Mastering Bitcoin

Andreas M. Antonopoulos / O'Reilly Media / 2014-12-20 / USD 34.99

Mastering Bitcoin tells you everything you need to know about joining one of the most exciting revolutions since the invention of the web: digital money. Bitcoin is the first successful digital curren......一起来看看 《Mastering Bitcoin》 这本书的介绍吧!

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

在线压缩/解压 JS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具