当前位置:网站首页>leetcode-374 猜数字大小
leetcode-374 猜数字大小
2022-04-23 15:45:00 【年中初界】
猜数字游戏的规则如下:
每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。
你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或 0):
-1:我选出的数字比你猜的数字小 pick < num
1:我选出的数字比你猜的数字大 pick > num
0:我选出的数字和你猜的数字一样。恭喜!你猜对了!pick == num
返回我选出的数字。
示例 1:
输入:n = 10, pick = 6
输出:6
示例 2:
输入:n = 1, pick = 1
输出:1
示例 3:
输入:n = 2, pick = 1
输出:1
示例 4:
输入:n = 2, pick = 2
输出:2
提示:
1 <= n <= 231 - 1
1 <= pick <= n
解法:
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
left, right = 1, n
while left < right:
mid = (left + right) // 2
if guess(mid) <= 0:
right = mid
else:
left = mid + 1
return left
版权声明
本文为[年中初界]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44536215/article/details/124353200
边栏推荐
- 字符串排序
- Neodynamic Barcode Professional for WPF V11.0
- Config组件学习笔记
- 单体架构系统重新架构
- 移动金融(自用)
- Named in pytoch_ parameters、named_ children、named_ Modules function
- 大厂技术实现 | 行业解决方案系列教程
- mysql乐观锁解决并发冲突
- IronPDF for . NET 2022.4.5455
- [backtrader source code analysis 18] Yahoo Py code comments and analysis (boring, interested in the code, you can refer to)
猜你喜欢
幂等性的处理
现在做自媒体能赚钱吗?看完这篇文章你就明白了
Codejock Suite Pro v20. three
多线程原理和常用方法以及Thread和Runnable的区别
Temporal model: long-term and short-term memory network (LSTM)
使用 Bitnami PostgreSQL Docker 镜像快速设置流复制集群
考试考试自用
API IX JWT auth plug-in has an error. Risk announcement of information disclosure in response (cve-2022-29266)
Redis主从复制过程
c语言---字符串+内存函数
随机推荐
What if the server is poisoned? How does the server prevent virus intrusion?
pywintypes. com_ Error: (- 2147221020, 'invalid syntax', none, none)
小程序知识点积累
Redis主从复制过程
服务器中毒了怎么办?服务器怎么防止病毒入侵?
Connect PHP to MSSQL via PDO ODBC
网站建设与管理的基本概念
MySQL集群模式与应用场景
Use bitnami PostgreSQL docker image to quickly set up stream replication clusters
Modèle de Cluster MySQL et scénario d'application
Pgpool II 4.3 Chinese Manual - introductory tutorial
API IX JWT auth plug-in has an error. Risk announcement of information disclosure in response (cve-2022-29266)
s16.基于镜像仓库一键安装containerd脚本
Introduction to dynamic programming of leetcode learning plan day3 (198213740)
Node. JS ODBC connection PostgreSQL
Basic concepts of website construction and management
大型互联网为什么禁止ip直连
Calculate the number of occurrences of a character
【递归之数的拆分】n分k,限定范围的拆分
CAP定理