当前位置:网站首页>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
边栏推荐
猜你喜欢

Single architecture system re architecture

Pgpool II 4.3 Chinese Manual - introductory tutorial

布隆过滤器在亿级流量电商系统的应用

cadence SPB17. 4 - Active Class and Subclass

IronPDF for . NET 2022.4.5455

一刷314-剑指 Offer 09. 用两个栈实现队列(e)

基于 TiDB 的 Apache APISIX 高可用配置中心的最佳实践

Recommended search common evaluation indicators

IronPDF for .NET 2022.4.5455

MySQL optimistic lock to solve concurrency conflict
随机推荐
One brush 314 sword finger offer 09 Implement queue (E) with two stacks
Use bitnami PostgreSQL docker image to quickly set up stream replication clusters
Mobile finance (for personal use)
One brush 312 - simple repetition set - Sword finger offer 03 Duplicate number in array (E)
fatal error: torch/extension. h: No such file or directory
负载均衡器
String sorting
Codejock Suite Pro v20. three
Recommended search common evaluation indicators
Accumulation of applet knowledge points
开源项目推荐:3D点云处理软件ParaView,基于Qt和VTK
大型互联网为什么禁止ip直连
What role does the software performance test report play? How much is the third-party test report charged?
Basic concepts of website construction and management
Go language slice, range, set
Neodynamic Barcode Professional for WPF V11. 0
小程序知识点积累
移动金融(自用)
怎么看基金是不是reits,通过银行购买基金安全吗
What are the mobile app software testing tools? Sharing of third-party software evaluation