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;
    }
};
相关推荐
lkbhua莱克瓦244 小时前
Java基础——方法
java·开发语言·笔记·github·学习方法
catchadmin4 小时前
PHP 依赖管理器 Composer 2.9 发布
开发语言·php·composer
范纹杉想快点毕业5 小时前
《嵌入式开发硬核指南:91问一次讲透底层到架构》
java·开发语言·数据库·单片机·嵌入式硬件·mongodb
毕设源码-邱学长5 小时前
【开题答辩全过程】以 基于Python的Bilibili平台数据分析与可视化实现为例,包含答辩的问题和答案
开发语言·python·数据分析
StarPrayers.5 小时前
自蒸馏学习方法
人工智能·算法·学习方法
芝麻馅汤圆儿5 小时前
c文件编译
c语言·开发语言
大锦终5 小时前
【动规】背包问题
c++·算法·动态规划
千疑千寻~5 小时前
【Qt】QT的程序打包
开发语言·qt
咚咚王者5 小时前
人工智能之编程进阶 Python高级:第十一章 过渡项目
开发语言·人工智能·python
大G的笔记本5 小时前
Java常见设计模式面试题(高频)
java·开发语言·设计模式