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;
    }
};
相关推荐
PC2005-cloud3 分钟前
DSH 白嫖指南:接入 Command Code Go、WorkBuddy 与 Trae 的免费额度
开发语言·后端·golang
大熊背18 分钟前
IspPipeline色相旋转模块实现
人工智能·算法·计算机视觉
爱学习的小白柏19 分钟前
同城双活的核心不是双活,是逼着数据别出机房
大数据·人工智能·算法·langchain·ai编程
千里码aicood22 分钟前
基于Python语言的测量程序设计
开发语言·python
charlie11451419126 分钟前
C++ 的新标准容器:flat_map、inplace_vector 与 mdspan
开发语言·c++·开源项目
鹿角片ljp28 分钟前
LeetCode 31:下一个排列|右找小,右找大,交换,右反转
java·数据结构·算法
唠玖馆1 小时前
c++AVL树
开发语言·c++
2401_858286111 小时前
130.【C语言】可变参数宏
c语言·开发语言
霸道流氓气质1 小时前
通义千问 VL & Audio:图像、视频、语音多模态 Java 集成深度解析
java·开发语言·音视频
jayson.h1 小时前
python-可视化提取表格-通用
开发语言·python