当前位置:网站首页>二分查找
二分查找
2022-07-24 03:06:00 【算法与编程之美】
引言
二分查找是基础算法的一种,有利于我们提高查找效率。问题
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示列1:
输入:nums = [-1, 0, 3, 5, 9, 12, 54, 60, 100], target = 9
输出:4
示例2:
输入:nums = [-1, 0, 3, 5, 12, 54, 60, 100], target = 9
输出:-1方法
应为该数组为升序数组。首先,设l,r分别为该数组第一个下标和最后一个,在找到中间值的下标mid = (l + r)// 2,最后将其进行比较,最后找到要找的target。实验结果与讨论
| def f(nums): l, r = 0, len(nums) - 1 while l < r: mid = (l + r) // 2 if nums[mid] >= target: r = mid else: l = mid + 1 return r |
5.结语
这是最典型的二分查找的运用,二分查找对于类似问题可以提高效率,但二分查找只能用于有序排列的数组,不能对无序数组进行操作。
边栏推荐
- 开源量子开发框架 Cirq
- Unity 消息推送
- Do securities companies really have principal guaranteed financial products?
- Ugui source code analysis - imaterialmodifier
- 198. House raiding
- SSM family financial management personal financial management system accounting system
- LCD1602 - binge 51
- Liveqing live broadcast on demand streaming media OBS streaming live broadcast how to obtain interface verification token video verification streamtoken and configure token validity
- (6) Decorator extension [email protected] Principle of use
- Redux Usage Summary
猜你喜欢
![[hdlbits questions] Verilog language (2) vectors](/img/eb/125c9a7781391dc53e37ce347a475d.png)
[hdlbits questions] Verilog language (2) vectors

Attack and defense world web practice area (backup, cookie, disabled_button)
[email protected] Principle of use"/>(6) Decorator extension [email protected] Principle of use

summernote富文本编辑器

Hcip --- BGP comprehensive experiment

Open source embedded sig in the openeuler community. Let's talk about its multi OS hybrid deployment framework

O3DE 的Lumberyard 游戏引擎

Microsoft win11/10 package manager Winget will support the installation of applications from zip files

SSM的技术论坛含前后台

动态规划-01背包问题
随机推荐
Doodle icons - a free commercial graffiti style icon library, cute, light and unique
go IO操作-文件写
rust allow dead_ code
Attack and defense world web practice area (backup, cookie, disabled_button)
Hcip --- BGP comprehensive experiment
Is the reverse repurchase of treasury bonds safe? How to open an account online?
O3DE 的Lumberyard 游戏引擎
Is it safe to open an account for Xiaobai stock? Can I apply online?
Some properties of differential array operation
Acwing 4498. pointer (DFS)
JVM initial
uva1445
summernote富文本编辑器
Unity 消息推送
Minimum exchange times
Honey, we are homeless now
Connected graph (day 72)
JS small game running bear and cat source code
The function of SIP account - tell you what is SIP line
Summernote supports custom video upload function