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;
    }
};
相关推荐
重生之后端学习3 分钟前
19. 删除链表的倒数第 N 个结点
java·数据结构·算法·leetcode·职场和发展
aini_lovee10 分钟前
严格耦合波(RCWA)方法计算麦克斯韦方程数值解的MATLAB实现
数据结构·算法·matlab
安特尼27 分钟前
推荐算法手撕集合(持续更新)
人工智能·算法·机器学习·推荐算法
橘子师兄32 分钟前
C++AI大模型接入SDK—环境搭建
开发语言·c++·人工智能
lkbhua莱克瓦2432 分钟前
JavaScript核心语法
开发语言·前端·javascript·笔记·html·ecmascript·javaweb
bubiyoushang88833 分钟前
基于MATLAB的近红外光谱与PLS方法测定药片有效成分含量的实现
开发语言·matlab
鹿角片ljp34 分钟前
力扣14.最长公共前缀-纵向扫描法
java·算法·leetcode
weixin_4331793335 分钟前
Hangman 猜字游戏使用列表List实现
开发语言·python
Remember_99338 分钟前
【数据结构】深入理解优先级队列与堆:从原理到应用
java·数据结构·算法·spring·leetcode·maven·哈希算法
偷星星的贼1138 分钟前
C++中的状态机实现
开发语言·c++·算法