当前位置:网站首页>The binary search boundary value processing based on leetcode35 is used to clarify the boundary value of the judgment condition using the idea of interval
The binary search boundary value processing based on leetcode35 is used to clarify the boundary value of the judgment condition using the idea of interval
2022-07-28 22:12:00 【i_ choose_ game】
Binary search ideas
Reprint , For self review and review
The idea of this article is very good , be used for Clarify the boundary value processing
be based on leetcode35
The subject , To insert the target value into the array , These are the four situations .
The target value precedes all elements of the array
The target value is equal to an element in the array
The position where the target value is inserted into the array
The target value is after all elements of the array
These four conditions have been confirmed , You can try to solve the problem .
Next, I will explain this problem from the solution of violence and dichotomy , Let's also talk about the binary search method .
Violence solution
Violent problem solving Not necessarily, the time consumption is very high , The key depends on the way of implementation , Like binary search, the time consumption is not necessarily very low , It's the same .
Violence solution C++ Code
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
// Deal with the following three situations respectively
// The target value precedes all elements of the array
// The target value is equal to an element in the array
// The position where the target value is inserted into the array
if (nums[i] >= target) {
// Once found to be greater than or equal to target Of num[i], that i It's what we want
return i;
}
}
// Where the target value is after all elements of the array
return nums.size(); // If target It's the biggest , perhaps nums It's empty , Then return to nums The length of
}
};
Time complexity :O(n)
Spatial complexity :O(1)
Dichotomy
Since the time complexity of the brute force solution is O(n), Just try using binary search .
The premise of this topic is that the array is an ordered array , This is also the basic condition of using binary search .
After that, everyone As long as you see that the array given in the interview question is an ordered array , Think about whether you can use dichotomy .
At the same time, the title also emphasizes that there are no duplicate elements in the array , Because once there's a repeating element , The element subscript returned by binary search method may not be unique .
Binary search involves many boundary conditions , The logic is simple , It's just that it can't be written well .
I believe many students do not handle the boundary conditions well in the binary search method .
For example, what is it while(left < right) still while(left <= right), What is the right = middle Well , Still right = middle - 1 Well ?
It's not clear here mainly because The definition of interval is not clear , This is the invariant .
In the process of binary search , Keep invariants , This is the loop invariant ( Interested students can check ).
Dichotomy the first way to write
Take this topic as an example , The following code defines target It's in an interval that's left closed and right closed , That is to say [left, right] ( This is very important ).
This determines how the dichotomy code is written , Here's the code :
You should read the notes carefully , Think about why you write while(left <= right), Why write right = middle - 1.
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int left = 0;
int right = n - 1; // Definition target In a left closed right closed interval ,[left, right]
while (left <= right) {
// When left==right, Section [left, right] Is still valid
int middle = left + ((right - left) / 2);// Prevent overflow Equate to (left + right)/2
if (nums[middle] > target) {
right = middle - 1; // target In the left range , therefore [left, middle - 1]
} else if (nums[middle] < target) {
left = middle + 1; // target In the right range , therefore [middle + 1, right]
} else {
// nums[middle] == target
return middle;
}
}
// Deal with the following four situations respectively
// The target value precedes all elements of the array [0, -1]
// The target value is equal to an element in the array return middle;
// The position where the target value is inserted into the array [left, right],return right + 1
// Where the target value is after all elements of the array [left, right], This is a right closed interval , therefore return right + 1
return right + 1;
}
};
Time complexity :O(logn)
Time complexity :O(1)
Dichotomy the second way to write
If the definition target It's in a zone that's closed on the left and open on the right , That is to say [left, right) .
The boundary treatment of dichotomy is quite different .
The invariant is [left, right) The range of , The following code shows how invariants are persisted in loops .
You should read the notes carefully , Think about why you write while (left < right), Why write right = middle.
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
int left = 0;
int right = n; // Definition target In the interval between left closed and right open ,[left, right) target
while (left < right) {
// because left == right When , stay [left, right) It's invalid space
int middle = left + ((right - left) >> 1);
if (nums[middle] > target) {
right = middle; // target In the left range , stay [left, middle) in
} else if (nums[middle] < target) {
left = middle + 1; // target In the right range , stay [middle+1, right) in
} else {
// nums[middle] == target
return middle; // When the target value is found in the array , Return the subscript directly
}
}
// Deal with the following four situations respectively
// The target value precedes all elements of the array [0,0)
// The target value is equal to an element in the array return middle
// The position where the target value is inserted into the array [left, right) ,return right that will do
// Where the target value is after all elements of the array [left, right), This is the right opening section ,return right that will do
return right;
}
};
Time complexity :O(logn) Time complexity :O(1)
summary
I hope that through this topic , You will find that you usually write dichotomy , Why can't you write well , Because the definition of interval is not clear .
Determine whether the interval to be searched is left closed and right open [left, right), Still left closed and closed [left, right], This is the invariant .
And then in In the loop of binary search , Adhere to the principle of loop invariants , A lot of details , Naturally, you will know how to deal with .
above , It's my personal records , in my opinion , The truth is infinite , Infinite progress !
I'm a chestnut , I wish you happiness .
边栏推荐
- Save 70% of the video memory and increase the training speed by 2 times! Zheda & Ali proposed online convolution re parameterization orepa, and the code has been open source! (CVPR 2022 )
- Aimbetter insight into your database, DPM and APM solutions
- Esp8266 Arduino programming example - timer and interrupt
- 笔试总结记录
- Implementation of sequence table
- No swagger, what do I use?
- Make trouble fishing day by day
- HCIP(8)
- 39. 组合总和
- What technology is needed for applet development
猜你喜欢
Learning notes and summary of C language programming specification
Kubeedge releases white paper on cloud native edge computing threat model and security protection technology
Which brand is the best and most cost-effective open headset
Apifox:满足你对 Api 的所有幻想
Record the fluent to solve the problem of a renderflex overflowed by 7.3 pixels on the bottom
How is nanoid faster and more secure than UUID implemented? (glory Collection Edition)
开放式耳机哪个音质好、公认音质好的气传导耳机推荐
中国科学家首次用DNA构造卷积人工神经网络,可完成32类分子模式识别任务,或用于生物标志物信号分析和诊断
Kubevera plug-in addons download address
HCIP(11)
随机推荐
Matlab | basic knowledge summary I
深度学习必备:对数据集的拆分、根据拆分图片拆分labels、对全部标注标签进行区间检查
How to establish a decentralized community in Web3
Object based real-time spatial audio rendering - Dev for dev column
Wechat applet development company, do you know how to choose?
[NLP] generate word cloud
节省70%的显存,训练速度提高2倍!浙大&阿里提出在线卷积重新参数化OREPA,代码已开源!(CVPR 2022 )
第 8 篇:创建摄像机类
迪赛智慧数——折线图(堆叠面积图):2022年不同职业人群存款额占月收入比例排名
IFLYTEK written examination
hcip实验(15)
JS DOM编程之平平无奇小练习
【云原生之kubernetes】在kubernetes集群下的映射外部服务—Eendpoint
Esp8266 Arduino programming example - timer and interrupt
04. Default value of toref
HCIA comprehensive experiment (take Huawei ENSP as an example)
搞事摸鱼一天有一天
AimBetter洞察您的数据库,DPM 和 APM 解决方案
kali里的powersploit、evasion、weevely等工具的杂项记录
openresty 请求鉴权