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;
    }
};
相关推荐
征途菜哥几秒前
毛笔书体检测-hog+svm python opencv源码
算法·机器学习·支持向量机
大胆飞猪7 分钟前
dfs二叉树中的深搜(回溯、剪枝)--力扣129、814、230、257
算法·leetcode·深度优先·dfs
我不会JAVA!13 分钟前
C++ 实现A*算法
c++·算法
mushangqiujin17 分钟前
python爬虫 线程,进程,协程
开发语言·爬虫·python
一叶祇秋21 分钟前
Leetcode - 双周赛135
算法·leetcode·职场和发展
小王努力学编程27 分钟前
贪心算法学习C++
开发语言·c++·学习·算法·leetcode·贪心算法
羽沢3134 分钟前
js高级_执行上下文和作用域
开发语言·javascript·ecmascript
墨客Y36 分钟前
ubtuntu+cmake+c++
开发语言·c++
无限大637 分钟前
数据结构与算法入门 Day 0:程序世界的基石与密码
后端·算法·程序员
北京地铁1号线38 分钟前
菊厂20250416软件机考T2解答(200分)
python·算法