LeetCode374. Guess Number Higher or Lower——二分查找

文章目录

一、题目

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 will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

-1: Your guess is higher than the number I picked (i.e. num > pick).

1: Your guess is lower than the number I picked (i.e. num < pick).

0: your guess is equal to the number I picked (i.e. num == pick).

Return the number that I picked.

Example 1:

Input: n = 10, pick = 6

Output: 6

Example 2:

Input: n = 1, pick = 1

Output: 1

Example 3:

Input: n = 2, pick = 1

Output: 1

Constraints:

1 <= n <= 231 - 1

1 <= pick <= n

二、题解

cpp 复制代码
/** 
 * Forward declaration of guess API.
 * @param  num   your guess
 * @return 	     -1 if num is higher than the picked number
 *			      1 if num is lower than the picked number
 *               otherwise return 0
 * int guess(int num);
 */

class Solution {
public:
    int guessNumber(int n) {
        int l = 1,r = n;
        while(l <= r){
            int mid = l + ((r - l) >> 1);
            if(guess(mid) == 0) return mid;
            else if(guess(mid) == 1) l = mid + 1;
            else r = mid - 1;
        }
        return 0;
    }
};
相关推荐
编程阿峰8 分钟前
Python 环境配置(二)安装jupyter、matplotlib、numpy库
开发语言·python·jupyter·numpy·matplotlib
磁爆步兵29 分钟前
内存分区:程序运行的核心秘密
java·开发语言·jvm
此生决int1 小时前
深入理解C++系列(06)——模版初阶与STL
开发语言·c++
c238561 小时前
《枚举算法 “翻译官”:用 enum class 给 “游游的礼盒” 算分》
c语言·c++·算法
swany1 小时前
同步数据中,只需要几秒钟 & milvus向量数据库不可用 dify1.16.1 升级后踩坑记录
开发语言·python·numpy
小杍随笔1 小时前
2025年Rust GUI框架实战万字避坑指南
开发语言·后端·rust
noipp1 小时前
推荐题目:洛谷 P5843 [SCOI2012] Blinker 的噩梦
c语言·数据结构·c++·算法·游戏·洛谷·luogu
极客BIM工作室1 小时前
OpenCascade 倒角(Chamfer)算法完整逻辑解析
算法
geovindu1 小时前
CSharp: LogHelper
开发语言·后端·c#·.net
奈斯先生Vector2 小时前
大模型 Agentic Workflow 架构解构:异构 API 调度与 Token 路由的多模态系统设计
开发语言·前端·架构·prompt·aigc·音视频