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;
    }
};
相关推荐
Qimooidea6 分钟前
祁木 CAD Translator 深度评测:从参数解析到工程交付实战
java·开发语言·人工智能·机器翻译
小白学大数据18 分钟前
企业内网场景下 Python 自定义 CA 证书信任链的正确配置方法
开发语言·网络·python·信任链
不要葱花29 分钟前
接下来我将复现 10 篇强化学习算法:第 3 篇,一杯喜茶,搞定 Search-R1
算法·面试
Java面试题总结30 分钟前
使用 Python 在 Excel 中添加和自定义文本框
开发语言·python·excel
geovindu42 分钟前
CSharp: Recursion Algorithm
开发语言·后端·算法·c#·递归算法
dsyyyyy11011 小时前
用JavaScript实现排序算法
开发语言·javascript·排序算法
z小猫不吃鱼1 小时前
ResRep: Lossless CNN Pruning via Decoupling Remembering and Forgetting
算法·cnn·剪枝
卡提西亚1 小时前
leetcode-239. 滑动窗口最大值
算法·leetcode·职场和发展
CHANG_THE_WORLD1 小时前
逐层拆解:C++ 虚函数从对象内存到手工调用的完整过程
java·开发语言·c++
Scott9999HH1 小时前
2026 避坑实录:国产品牌压力变送器什么牌子好?从硬件抗扰到 C++ Qt 实时曲线绘制源码剖析
开发语言·c++·qt