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
相关推荐
Zwawa7 分钟前
卡尔曼到底在算什么:从一维到它的变式以及工程版卡尔曼滤波算法C语言实现
c语言·算法·嵌入式
电科_银尘20 分钟前
【大模型算法与工程 14】Tokenizer与Embedding:文本如何变成模型输入
算法·embedding
饮水桶_T1 小时前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
文丑颜不良啊3 小时前
LeetCode3281~3300题目解析
java·leetcode
地平线开发者4 小时前
让 AI Agent 和 征程6 台架高效、稳定、安全地协作
算法·安全·自动驾驶
kyle~5 小时前
SHA-256 哈希去重
算法·哈希算法
文丑颜不良啊7 小时前
LeetCode3261~3280题目解析
java·leetcode
风落青芜8 小时前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
Rain的Java大神之路9 小时前
LeetCode 40 组合总和 II:面试官想听的不是回溯,而是那行去重代码
java·leetcode·面试
青少儿编程课堂9 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中国剩余定理解析
c++·python·算法·bfs·信息学竞赛