当前位置:网站首页>二分查找的细节坑
二分查找的细节坑
2022-07-31 15:55:00 【左手八嘎呀路】
二分查找的坑
介绍
- 二分查找是一个十分容易理解的一中算法,原理非常的简单,就是不断取出中间值进行对比,最终得出结果(这里不做过多介绍)
问题
- 二分查找容易写错
- 循环的判断条件有时候可以,有时候又不行
- 中间值索引取值,left/right = mid? mid+1? mid-1?
- 不一样的题用同样的二分查找就出现各种问题?
分析
先随机打开一个力扣的简单题,看看别人的题解
- 首先第一个坑是mid的溢出问题
这里不做介绍,一般都是用: (大 - 小) / 2 + 小
等价于:(大 + 小)/ 2
- 循环条件问题
自己写的时候,有时候的循环条件没问题,有时候就这么也跳不出循环,看别人的题解的条件又是五花八门
- 高低移位问题
高低移位也是和循环条件差不多,题解五花八门,和循环条件又紧紧相关
解决
视频链接:https://www.bilibili.com/video/BV1d54y1q7k7?spm_id_from=333.337.search-card.all.click
其实二分查找还是容易被忽视的,有非常多的细节,看了大佬的讲解收获还是比较大的,至少固定了属于自己的模板,在实际刷题就没有那么多烦恼和问题
- 循环条件
left + 1 < right
- 移位(没有±1的问题)
left/right = mid
- 返回(没有返回left/right的问题)
mid
边栏推荐
- "Autumn Recruitment Series" MySQL Interview Core 25 Questions (with answers)
- Website vulnerability repair service provider's analysis of unauthorized vulnerability
- EF Core 2.2中将ORM框架生成的SQL语句输出到控制台
- The 2nd China PWA Developer Day
- 6-22 Vulnerability exploit - postgresql database password cracking
- How Redis handles concurrent access
- button控件的使用
- 01 邂逅typescript,环境搭建
- 更新数据表update
- i.MX6ULL驱动开发 | 33 - NXP原厂网络设备驱动浅读(LAN8720 PHY)
猜你喜欢
Tencent Cloud Deployment----DevOps
How Redis handles concurrent access
2022年整理LeetCode最新刷题攻略分享(附中文详细题解)
BGP综合实验(建立对等体、路由反射器、联邦、路由宣告及聚合)
对话庄表伟:开源第一课
Grafana安装后web打开报错
The use of border controls
Internet banking stolen?This article tells you how to use online banking safely
Browser's built-in color picker
第05章 存储引擎【1.MySQL架构篇】【MySQL高级】
随机推荐
11 pinia use
2022年必读的12本机器学习书籍推荐
更新数据表update
Deployment应用生命周期与Pod健康检查
LeetCode_733_Image rendering
复制延迟案例(3)-单调读
tensorflow2.0 cnn(layerwise)
Insert into data table to insert data
Codeforces Round #796 (Div. 2) (A-D)
Linux check redis version (check mongodb version)
Replication Latency Case (1) - Eventual Consistency
What is the difference between BI software in the domestic market?
The principle of hough transform detection of straight lines (opencv hough straight line detection)
Vb how to connect mysql_vb how to connect to the database collection "advice"
[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development
字符串反转的实现方法总结「建议收藏」
tensorflow2.0 cnn(layerwise)
MySQL常用语句整理
The new BMW 3 Series is on the market, with safety and comfort
Doing things software development - the importance of law and understanding of reasonable conclusions