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
相关推荐
2301_7644413310 分钟前
Factorization Machine(FM模型,因子分解机)
python·算法
少许极端23 分钟前
算法奇妙屋(五十二)-备战+复习2
java·算法
luj_176823 分钟前
硝酸核关联假说缺乏实验证据
c语言·开发语言·c++·经验分享·算法
青梅橘子皮1 小时前
Linux---虚拟地址空间
linux·运维·算法
KaMeidebaby1 小时前
卡梅德生物技术快报|酵母表达系统工程:裂殖酵母穿梭载体分子改造与载体构建技术总结
网络·人工智能·网络协议·tcp/ip·算法
HZ·湘怡1 小时前
二叉树 1
数据结构·算法·二叉树·
吴可可1231 小时前
AutoCAD 2024搭配C#开发最佳实践
算法
Stick_ZYZ1 小时前
从 Prompt 到 Context Engineering:Agent 真正稳定的关键
大数据·人工智能·算法·ai·prompt
ZHW_AI课题组1 小时前
使用Stable Diffusion v1.5文本引导与无分类器引导(CFG)算法实现条件生成图片
人工智能·python·算法·机器学习·stable diffusion