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
相关推荐
X journey6 小时前
机器学习进阶(13):支持向量机SVM
算法·机器学习·支持向量机
洛水水6 小时前
【力扣100题】30.二叉树的直径
算法·leetcode·职场和发展
gihigo19987 小时前
Bezier曲线曲面生成算法
算法
平行侠7 小时前
024多精度大整数 - 突破硬件精度限制的任意精度运算
数据结构·算法
IronMurphy8 小时前
【算法四十五】139. 单词拆分
算法
洛水水9 小时前
【力扣100题】32.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
如竟没有火炬9 小时前
用队列实现栈
开发语言·数据结构·python·算法·leetcode·深度优先
云栖梦泽在10 小时前
AI安全入门:AI模型泄露的风险与防护措施
人工智能·算法·动态规划
水木流年追梦10 小时前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
洛水水10 小时前
【力扣100题】31.二叉树的层序遍历
算法·leetcode·职场和发展