博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Guess Number Higher or Lower 猜数字大小
阅读量:7056 次
发布时间:2019-06-28

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

 

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.

这道题是一道典型的猜价格的问题,根据对方说高了还是低了来缩小范围,最简单快速的方法就是折半搜索法,原理很简单,参见代码如下:

 

// Forward declaration of guess API.// @param num, your guess// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0int guess(int num);class Solution {public:    int guessNumber(int n) {        if (guess(n) == 0) return n;        int left = 1, right = n;        while (left < right) {            int mid = left + (right - left) / 2, t = guess(mid);            if (t == 0) return mid;            else if (t == 1) left = mid;            else right = mid;        }        return left;    }};

 

类似题目:

 

 

转载地址:http://lslol.baihongyu.com/

你可能感兴趣的文章
《Elixir in Action》书评及作者问答录
查看>>
Apache HBase的现状和发展
查看>>
AlphaZero进化论:从零开始,制霸所有棋类游戏
查看>>
IBM中国开发中心吉燕勇: 通过Cloud Data Services打造新型认知计算数据分析云平台...
查看>>
作者问答:解密硅谷
查看>>
linux系统高并发socket最大连接数优化
查看>>
Netflix发布Polly.JS,一个用于HTTP交互的开源库
查看>>
敏捷团队中测试人员的角色
查看>>
GitHub推出Scientist,帮助开发者重构关键路径代码
查看>>
40%创业公司用伪AI忽悠钱,欧洲被AI时代抛弃了吗?
查看>>
AT&T签署8位数合同,设备商恐无法从5G获利
查看>>
Netflix Play API:我们为什么构建了一个演进式架构?
查看>>
我不是仆人,是主人!敏捷中领导力的新比喻?
查看>>
Next.js 7.0正式发布:重新编译速度提高42%,支持WebAssembly
查看>>
Java API for RESTful Web Services 2.1发布
查看>>
Visual Studio 2017 15.8第一个预览版发布,支持ARM64
查看>>
Java日志性能那些事
查看>>
Invokedynamic:Java的秘密武器
查看>>
Raffi Krikorian 为“在运行中进行架构重写”提供了指南
查看>>
Plaid.com的监控系统如何实现与9600多家金融机构的集成
查看>>