Leetcode 374. Guess Number Higher or Lower

Problem

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.

Algorithm

Bineary search.

Code

python3 复制代码
# The guess API is already defined for you.
# @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
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        L, R = 1, n
        while L < R:
            Mid = int((L + R) / 2)
            g = guess(Mid)
            if g == 0:
                return Mid
            elif g > 0:
                L = Mid + 1
            else:
                R = Mid - 1
        return L
相关推荐
Tisfy1 分钟前
LeetCode 3010.将数组分成最小总代价的子数组 I:排序 OR 维护最小次小
算法·leetcode·题解·排序·最小次小值
Learn Beyond Limits6 分钟前
文献阅读:A Probabilistic U-Net for Segmentation of Ambiguous Images
论文阅读·人工智能·深度学习·算法·机器学习·计算机视觉·ai
m0_7369191017 分钟前
编译器命令选项优化
开发语言·c++·算法
naruto_lnq24 分钟前
C++中的工厂方法模式
开发语言·c++·算法
千逐-沐风34 分钟前
SMU-ACM2026冬训周报2nd
算法
m0_748233171 小时前
C#与C语言:5大核心语法共性
java·jvm·算法
痴儿哈哈1 小时前
C++与硬件交互编程
开发语言·c++·算法
小O的算法实验室1 小时前
2024年ESWA SCI1区TOP,异构无人机配送问题的集成多目标优化方法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
草履虫建模2 小时前
力扣算法 121. 买卖股票的最佳时机
算法·leetcode·职场和发展·贪心算法·动态规划·一次遍历
养军博客2 小时前
C语言五天速成(可用于蓝桥杯备考 难度中等偏下)
c语言·算法·蓝桥杯