当前位置:网站首页>二分查找3 - 猜数字大小
二分查找3 - 猜数字大小
2022-08-03 05:25:00 【花开花落夏】
猜数字大小
一 题目
猜数字游戏的规则如下:
每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。
你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或 0):
-1:我选出的数字比你猜的数字小 pick < num
1:我选出的数字比你猜的数字大 pick > num
0:我选出的数字和你猜的数字一样。恭喜!你猜对了!pick == num
返回我选出的数字。
来源:力扣(LeetCode)

二 解题
此题为经典的二分查找题目,其中最大的坑是计算mid时,left+right内存溢出,因此使用left + (right-left)/2来计算mid,防止内存溢出。
/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is lower than the guess number * 1 if num is higher than the guess number * otherwise return 0 * int guess(int num); */
public class Solution extends GuessGame {
public int guessNumber(int n) {
int num=n;
int guessResult,left=1,right=n;
while(left<=right){
num = left + (right-left)/2;
guessResult = guess(num);
if(guessResult==0){
break;
}else if(guessResult==-1){
right=num-1;
}else if(guessResult==1){
left=num+1;
}
}
return num;
}
}

边栏推荐
猜你喜欢

自监督论文阅读笔记 Self-supervised Learning in Remote Sensing: A Review

Windos 内网渗透之Token的使用

ZEMAX | 探索 OpticStudio中的序列模式

自监督论文阅读笔记 Self-Supervised Deep Learning for Vehicle Detection in High-Resolution Satellite Imagery

微信小程序 自定义tabBar

各种cms getshell技巧

神经网络之感知机

Dynamic adjustment of web theme (2) Extraction

自监督论文阅读笔记 SimCLRV2 Big Self-Supervised Models are Strong Semi-Supervised Learners

【第三周】ResNet+ResNeXt
随机推荐
极光推送 能否缓存 消息
虚拟地址空间布局
A.1#【内存管理】——1.1.4 node: 初始化
自监督论文阅读笔记Reading and Writing: Discriminative and Generative Modelingfor Self-Supervised Text Recogn
new / malloc / delete / free之间的区别
各种cms getshell技巧
ARMv8 架构----armv8 类别
【七夕特效】 -- 满屏爱心
自监督论文阅读笔记 Multi-motion and Appearance Self-Supervised Moving Object Detection
增强光学系统设计 | Zemax 全新 22.2 版本产品现已发布!
队列方法接收串口的数据
神经网络基础
cb板上常用的电子元器件都有哪些?
VS2022 encapsulation under Windows dynamic library and dynamic library calls
5. What is the difference between int and Integer?
全球一流医疗技术公司如何最大程度提高设计工作效率 | SOLIDWORKS 产品探索
VSCODE 常见问题
什么是参数化设计,通过实操了解一下? | SOLIDWORKS 操作视频
classpath:与classpath*的比较
Windos 内网渗透之Token的使用