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
相关推荐
csdn_aspnet3 小时前
C++ 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
c++·算法
逐米时代6 小时前
「制造新解法」行业对标方法:借鉴而不照搬的最佳实践
人工智能·算法·制造
kyrie_sakura6 小时前
大模型学习32 --大模型微调3 -- 分布式训练算法
分布式·学习·算法
Rabitebla6 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树
linux·运维·服务器·c++·笔记·学习·算法
m0_743106467 小时前
SAD-GS:从梯度邻域到频率驱动表达3D空间
人工智能·算法·计算机视觉·3d·几何学
csdn_aspnet7 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
java·算法
专注仿真9 小时前
仿真智能体训练(评估指标篇):任务完成率算法详解与实战
人工智能·算法·机器学习·afsim智能体·仿真训练·afsim智能体训练·任务完成率算法
小手cool9 小时前
二分查找:在有序数组中查找最接近 target 的元素索引
java·数据结构·算法
zmzb01039 小时前
C++课后习题训练记录Day216
数据结构·c++·算法
INGNIGHT10 小时前
leetcode尊享100题
算法·哈希算法