algorithm - 使用 mid=first+(last-first)/2 代替 (first+last)/2 的效果
问题描述
为什么人们使用mid=first+(last-first)/2 而不是(first+last)/2,在二分查找的情况下) 两者有区别吗。如果有,请告诉我,因为我无法理解其中的区别。
解决方案
如果使用mid = (first + last) / 2
then 有可能在 first 或 last 为 时溢出MAX
,即当 first 或 last 为最大值或范围时,再添加一个数字将溢出。
所以我们使用mid = first + (last-first) / 2
, 因为即使 first 或 last 是范围的最大值,它也不会溢出。
此外,在竞争性编程测试用例中,将测试您的代码以适应极端场景,很可能其中一个测试用例具有这些最大范围数。所以建议使用mid = first + (last-first)/2
推荐阅读
- discord.js - discord.js 检查用户和机器人是否在同一个语音通道中
- c++ - 调试一个简单的函数
- algorithm - 算法求助:给定一个num,最后能不能是1
- python - 我无法通过 AWS SES 发送带有主题的电子邮件
- javascript - 删除滑动延迟香草js
- javascript - 未捕获的类型错误:$(...).popover 不是函数
- javascript - 签名板未检测到任何点击,因此未绘图
- java - 在 WebSocket 控制器中获取登录用户的 Principal
- vb.net - 将字符串转换为文本框名称
- python - 使用 Scapy 读取 20 GB 文件