当前位置:网站首页>[day 26] given the ascending array nums of n elements, find a function to find the subscript of target in nums | learn binary search
[day 26] given the ascending array nums of n elements, find a function to find the subscript of target in nums | learn binary search
2022-06-25 02:07:00 【Executory peduncle】
Learning Guide
order 、 Column Preface
This column opens , The purpose is to help everyone better master learning Java, Especially some Java Learners' It is difficult to find systematic algorithm learning materials on the Internet to help you get started with algorithms , At the same time, if you have any questions about the contents of the column, you can add my wechat at the end of the article to give you a one-to-one explanation .
But the most important thing is to think independently , For all the content of this column , Be able to fully master , Write the code completely by yourself , There must be no problem getting started with the algorithm .
The learning of algorithm must not be short of summary , Here I recommend that you can go to University algorithm community Punch in the learned knowledge , To consolidate and review .
The only way to learn algorithms well must be Topic sea strategy , Only by accumulating a lot of practice can you practice your skills . Any topic of the column I will start with 【 Title Description 】【 Their thinking 】【 Template code 】【 Code parsing 】 Wait for four plates to explain .
order 、 Preface of this chapter
Today's content is very important , The first involves binary search , This is a classic in a classic , The foundation in the foundation , But it is also an algorithm that can torture and kill a large number of people . Anywhere , It is a very important test site , Today we are just beginning to touch on .
Two points search
Binary search is an optimization algorithm , It can usually O ( n ) O(n) O(n) The search complexity is optimized to O ( l o g n ) O(logn) O(logn). The premise of using binary search is that —— Dichotomy . Many people always have misunderstandings , Using binary search must have monotonicity , This view is wrong , Monotonicity is only one kind of the duality , It is the scene that we often encounter that can use dichotomy , In fact, if we satisfy the duality, we can divide into two .
So what is Dichotomy Well ?
For a range of data , There is a critical point , Make all the data on one side of the critical point satisfy a certain property , Neither side satisfies this property .
Dichotomy has a core check function , The logic of this function is to find the properties of this critical condition , Make both sides satisfied , Neither side is satisfied . When our mid Fall on the interval satisfying the property , We will keep this point , When it falls on an unsatisfied interval , We'll round off the point , Finally, the left and right pointers will approach this critical point infinitely and exit the loop , We got the answer .
One 、【 Example 1】
1、 Title Description
Given a
n( 1 ≤ n ≤ 10000 ) (1 \leq n \leq 10000) (1≤n≤10000) The elements are ordered ( Ascending ) integer arraynumsAnd a target valuetarget, Write a function searchnumsMediumtarget, If the target value has a return subscript , Otherwise return to-1. Ensure that there are no duplicate elements in the array
2、 Their thinking
- ( 1 ) (1) (1) Like the main core of binary search , Is to look for duality , For arrays with monotonicity, it is good to find the duality . Because the array is in ascending order , We know that for
targetThe elements on the left must be less thantarget, abouttargetThe element on the right , Must be greater than or equal totarget( This right side includestargetThe location of ), So we can find the duality . - ( 2 ) (2) (2) Combined with the above analysis , When
midFall in a non-conforming range , We makel=mid+1, Because the non-conforming interval is on the left , When it falls in a consistent range , We maker=mid, Because the matching range is on the right , If... Exists in the arraytarget, Then, when the cycle is over, it should meetnums[l]==nums[r]==target, Otherwise, there is no solution .
3、 Template code
class Solution {
public int search(int[] nums, int target) {
int n=nums.length;
int l=0;
int r=n-1;
while(l<r){
int mid=l+r>>1;
if(nums[mid]>=target) r=mid;
else l=mid+1;
}
return nums[r]==target?r:-1;
}
}
4、 Code parsing
- ( 1 ) (1) (1) Why is the cyclic condition written as
l<r, instead ofl<=rWell ? becausel<rThe end condition of isl==r, herelandrIn one position , We don't have to worry about the answer in the endlUp orrOn , So it is recommended that everyone write this . - ( 2 ) (2) (2)
l+r>>1What does that mean? ?>>Is the shift right operator , In essence, it willl+rDivide the sum of by2, and(l+r)/2No difference between , It's just>>A little faster . Ifl+rAnd may explodeint, Should be written asr-l+l/2 - ( 3 ) (3) (3) Finally, why should we judge
nums[r]==target? Although the array satisfies the duality , It does not meantargetIt must be in the array , For example, there are arrays [ 1 , 2 , 4 , 5 ] [1,2,4,5] [1,2,4,5],targetby 3 Under the circumstances , Arrays are also binary , But the critical point in the original array does not necessarily have an answer .
3、 ... and 、 Recommendation column
Four 、 After-school exercises
| Serial number | Topic link | Difficulty rating |
|---|---|---|
| 1 | Two points search | 2 |
| 1 | Search insert location | 2 |
边栏推荐
- Numerical scheme simulation of forward stochastic differential equations with Markov Switching
- 内网学习笔记(6)
- Deoxyribonuclease I instructions in Chinese and English
- 获取图片外链的方法–网易相册[通俗易懂]
- Convert string array to list collection
- 股票开账户如何优惠开户?手机开户是安全么?
- Abnova BSG monoclonal antibody description in Chinese and English
- 元宇宙的生态圈
- Chinese address and English address
- 指南针靠谱吗?开证券账户安全吗?
猜你喜欢

2个NPN三极管组成的恒流电路

What are the reasons for the abnormal playback of the online channel of the channel accessed by easycvr national standard protocol?

中文地址与英文地址

Google browser console F12 how to set the Chinese / English switching method, we must see the last!!!

内网学习笔记(7)

Fake wireless speakers in stores? Sony responded: the product has reserved a wired connection interface, which can be used in complex scenarios

Multi modal data can also be Mae? Berkeley & Google proposed m3ae to conduct Mae on image and text data! The optimal masking rate can reach 75%, significantly higher than 15% of Bert

Pbcms adding cyclic digital labels

创新药二级市场审饼疲劳:三期临床成功、产品获批也不管用了

多模态数据也能进行MAE?伯克利&谷歌提出M3AE,在图像和文本数据上进行MAE!最优掩蔽率可达75%,显著高于BERT的15%
随机推荐
Intégration de la plate - forme de test continu open source de metersphere avec Alibaba Cloud Effect devops
MCN机构遍地开花:博主和作者要谨慎签约、行业水很深
EasyCVR平台EHOME协议接入,视频播放出现断流是什么原因?
Basic use of transformers Library
The ecosystem of the yuan universe
如何通过EasyCVR接口监测日志观察平台拉流情况?
Pbcms adding cyclic digital labels
同一服务器两个端口不同的应用session覆盖解决方案
Baidu voice synthesizes voice files and displays them on the website
AssertionError: CUDA unavailable, invalid device 0 requested
DataEase模板市场正式发布
[mobile terminal] design size of mobile phone interface
做软件安全测试的作用,如何寻找软件安全测试公司出具报告?
leetcode:2104. Subarray range and
Deoxyribonuclease I instructions in Chinese and English
Abnova a4gnt polyclonal antibody
数据库系统概论必背知识
Application session coverage solutions with different ports on the same server
左手梦想 右手责任 广汽本田不光关注销量 还有儿童安全
基本布局-QHBoxLayout类、QVBoxLayout类、QGridLayout类