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
相关推荐
jerryinwuhan31 分钟前
SVM案例分析
算法·机器学习·支持向量机
高山上有一只小老虎39 分钟前
购物消费打折
java·算法
郝学胜-神的一滴1 小时前
计算机图形中的法线矩阵:深入理解与应用
开发语言·程序人生·线性代数·算法·机器学习·矩阵·个人开发
m0_591338911 小时前
day8鹏哥C语言--函数
c语言·开发语言·算法
_OP_CHEN1 小时前
算法基础篇:(二)基础算法之高精度:突破数据极限
算法·acm·算法竞赛·高精度算法·oj题
一只老丸1 小时前
HOT100题打卡第30天——技巧
算法
Bi_BIT2 小时前
代码随想录训练营打卡Day38| 动态规划part06
算法·动态规划
手握风云-2 小时前
回溯剪枝的“减法艺术”:化解超时危机的 “救命稻草”(三)
算法·剪枝
元亓亓亓2 小时前
LeetCode热题100--46. 全排列--中等
算法·leetcode·职场和发展
墨染点香2 小时前
LeetCode 刷题【146. LRU 缓存】
leetcode·缓存·哈希算法