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
相关推荐
风中的微尘5 小时前
39.网络流入门
开发语言·网络·c++·算法
西红柿维生素6 小时前
JVM相关总结
java·jvm·算法
ChillJavaGuy8 小时前
常见限流算法详解与对比
java·算法·限流算法
sali-tec8 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
你怎么知道我是队长9 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒9 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
纪元A梦11 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_12 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls12 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客12 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法