当前位置:网站首页>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
边栏推荐
- WPS brand was upgraded to focus on China. The other two domestic software were banned from going abroad with a low profile
- Configuration of multi spanning tree MSTP
- Cookie&Session
- Why disable foreign key constraints
- 山寨版归并【上】
- For examination
- Multi level cache usage
- Single architecture system re architecture
- MySQL Cluster Mode and application scenario
- JVM - Chapter 2 - class loader subsystem
猜你喜欢
现在做自媒体能赚钱吗?看完这篇文章你就明白了
多级缓存使用
Special analysis of China's digital technology in 2022
The principle and common methods of multithreading and the difference between thread and runnable
CVPR 2022 优质论文分享
时序模型:门控循环单元网络(GRU)
MetaLife与ESTV建立战略合作伙伴关系并任命其首席执行官Eric Yoon为顾问
WPS品牌再升级专注国内,另两款国产软件低调出国门,却遭禁令
Sorting and replying to questions related to transformer
Configuration of multi spanning tree MSTP
随机推荐
c语言---字符串+内存函数
s16. One click installation of containerd script based on image warehouse
山寨版归并【上】
utils. Deprecated in35 may be cancelled due to upgrade. What should I do
Go language, array, pointer, structure
pywintypes.com_error: (-2147221020, ‘无效的语法‘, None, None)
vim指定行注释和解注释
Named in pytoch_ parameters、named_ children、named_ Modules function
Config组件学习笔记
Go语言数组,指针,结构体
Go language, condition, loop, function
Upgrade MySQL 5.1 to 5.67
For examination
幂等性的处理
MetaLife与ESTV建立战略合作伙伴关系并任命其首席执行官Eric Yoon为顾问
MySQL集群模式與應用場景
Upgrade MySQL 5.1 to 5.68
fatal error: torch/extension. h: No such file or directory
Calculate the number of occurrences of a character
基础贪心总结