当前位置:网站首页>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
边栏推荐
- [split of recursive number] n points K, split of limited range
- gps北斗高精度卫星时间同步系统应用案例
- 【自娱自乐】构造笔记 week 2
- What is CNAs certification? What are the software evaluation centers recognized by CNAs?
- 【开源工具分享】单片机调试助手(示波/改值/日志) - LinkScope
- Config组件学习笔记
- PHP 的运算符
- 通過 PDO ODBC 將 PHP 連接到 MySQL
- Pytorch中named_parameters、named_children、named_modules函数
- Special analysis of China's digital technology in 2022
猜你喜欢
Sorting and replying to questions related to transformer
Demonstration meeting on startup and implementation scheme of swarm intelligence autonomous operation smart farm project
IronPDF for .NET 2022.4.5455
Basic concepts of website construction and management
Load Balancer
Timing model: gated cyclic unit network (Gru)
移动金融(自用)
Independent operation smart farm Innovation Forum
Codejock Suite Pro v20. three
负载均衡器
随机推荐
Neodynamic Barcode Professional for WPF V11. 0
网站压测工具Apache-ab,webbench,Apache-Jemeter
PHP function
Recommended search common evaluation indicators
CAP定理
通過 PDO ODBC 將 PHP 連接到 MySQL
gps北斗高精度卫星时间同步系统应用案例
Advantages, disadvantages and selection of activation function
编译,连接 -- 笔记
PHP classes and objects
What role does the software performance test report play? How much is the third-party test report charged?
Deletes the least frequently occurring character in the string
Go language, condition, loop, function
为啥禁用外键约束
WPS brand was upgraded to focus on China. The other two domestic software were banned from going abroad with a low profile
现在做自媒体能赚钱吗?看完这篇文章你就明白了
String sorting
Cookie&Session
php类与对象
Go并发和通道