当前位置:网站首页>二分查找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;
}
}

边栏推荐
- MMU 介绍-[TBL/page table work]
- 微信小程序 自定义tabBar
- ASP.NET MVC:自定义 Route
- 自监督论文阅读笔记 Self-Supervised Deep Learning for Vehicle Detection in High-Resolution Satellite Imagery
- page fault-页异常流程
- IPC通信 - 管道
- ARMv8 架构----armv8 类别
- 自监督论文阅读笔记 SimCLRV2 Big Self-Supervised Models are Strong Semi-Supervised Learners
- ucos任务调度原理
- 九、请介绍类加载过程,什么是双亲委派模型?
猜你喜欢
随机推荐
二阶段提问总结
三分钟看懂二极管的所有基础知识点
MySql的Sql语句的练习(试试你能写出来几道呢)
自监督论文阅读笔记Reading and Writing: Discriminative and Generative Modelingfor Self-Supervised Text Recogn
基于南航app直减自动出票
自监督论文阅读笔记 DetCo: Unsupervised Contrastive Learning for Object Detection
最优化方法概述
自监督论文阅读笔记 TASK-RELATED SELF-SUPERVISED LEARNING FOR REMOTE SENSING IMAGE CHANGE DETECTION
VS2022 encapsulates static libraries and calls static libraries under window
电子元器件之电子变压器可分为哪几类?
什么是参数化设计,通过实操了解一下? | SOLIDWORKS 操作视频
自监督论文阅读笔记FIAD net: a Fast SAR ship detection network based on feature integration attention and self
常见的电容器有哪些?唯样商城
内网渗透之PPT票据传递攻击(Pass the Ticket)
进程间通讯 (IPC 技术) - 信号
2021-04-23
g++参数说明
servlet学习(七)ServletContext
【第一周】深度学习和pytorch基础
SQLMAP介绍及使用








