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;
    }
};
相关推荐
于慨2 分钟前
dayjs处理时区问题、前端时区问题
开发语言·前端·javascript
范纹杉想快点毕业6 分钟前
嵌入式C语言实战开发详解
linux·运维·算法
listhi52012 分钟前
基于MATLAB的LTE系统仿真实现
开发语言·matlab
闲看云起18 分钟前
LeetCode day3-最长连续序列
算法·leetcode
ss27320 分钟前
ScheduledThreadPoolExecutor异常处理
java·开发语言
TechNomad28 分钟前
二叉堆&大根堆&小根堆的介绍和使用
数据结构
ejjdhdjdjdjdjjsl28 分钟前
Winform初步认识
开发语言·javascript·ecmascript
随意起个昵称28 分钟前
【题解学习】序列题
学习·算法
思通数科多模态大模型32 分钟前
门店 AI 清洁系统:AI 语义分割 + 机器人清洁
大数据·人工智能·算法·目标检测·计算机视觉·自然语言处理·机器人
六毛的毛41 分钟前
比较含退格的字符串
开发语言·python·leetcode