当前位置:网站首页>[binary search] 34 Find the first and last positions of elements in a sorted array
[binary search] 34 Find the first and last positions of elements in a sorted array
2022-07-05 05:16:00 【lee2813】
One 、 subject
Given an array of integers in ascending order nums, And a target value target. Find the start and end position of the given target value in the array .
If the target value does not exist in the array target, return [-1, -1].
Advanced :
You can design and implement time complexity of O(log n) Does the algorithm solve this problem ?
Example 1:
Input :nums = [5,7,7,8,8,10], target = 8
Output :[3,4]
Example 2:
Input :nums = [5,7,7,8,8,10], target = 6
Output :[-1,-1]
Example 3:
Input :nums = [], target = 0
Output :[-1,-1]
Two 、 Answer key
Solution 1 : Search for ( Time consuming )
Solution 2 : Two points search
Because the array is monotonically increasing , We can use the binary search method to speed up the search process . Here is also set as the left closed right closed interval .
When finding the corresponding element to determine whether it is the position of the first occurrence and the last occurrence of the given value , Use the following strategies :
- Finding the first occurrence position of a given value is equivalent to finding the first greater than ( Because there may be cases without this value ) Subscript equal to the given value
- Finding the last occurrence position of a given value is equivalent to finding the first subscript larger than the given value , subtracting 1
Take finding the location of the first occurrence as an example , The search results are as follows :
- The lookup value does not match the target value ( Less than the target ): Take the left range
- The search value matches the target value ( Greater than equal target value ): Take the right range
- Left boundary > Right border : return
l, Because the matching situation here is greater than or equal to , Moving isl, Therefore, it returnsl
among , The method of using dichotomy to determine the position of elements for comparison is the same , The comparison strategy is different .
3、 ... and 、 Code
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.size()==0) return vector<int>{
-1,-1};
int leftindex = fun1(nums,target);
int rightindex = fun2(nums,target);
if(leftindex==nums.size() || nums[leftindex] != target) return vector<int>{
-1,-1};
return vector<int>{
leftindex,rightindex};
}
int fun1(vector<int>& nums,int target){
int l = 0,r = nums.size() - 1;
int mid;
while(l<=r){
mid = (l + r) / 2;
if(nums[mid] >= target) r = mid - 1;
else l = mid + 1;
}
return l;
}
int fun2(vector<int>& nums,int target){
int l = 0,r = nums.size() - 1;
int mid;
while(l<=r){
mid = (l + r) / 2;
if(nums[mid] > target) r = mid - 1;
else l = mid + 1;
}
return l-1;
}
};
边栏推荐
- 支持多模多态 GBase 8c数据库持续创新重磅升级
- Three dimensional dice realize 3D cool rotation effect (with complete source code) (with animation code)
- 2021-10-29
- Unity find the coordinates of a point on the circle
- Ue4/ue5 illusory engine, material chapter, texture, compression and memory compression and memory
- Under the national teacher qualification certificate in the first half of 2022
- [转]MySQL操作实战(三):表联结
- 【Leetcode】1352. Product of the last K numbers
- Unity intelligent NPC production -- pre judgment walking (method 1)
- [turn]: Apache Felix framework configuration properties
猜你喜欢

Django reports an error when connecting to the database. What is the reason

Grail layout and double wing layout

Stm32cubemx (8): RTC and RTC wake-up interrupt

Use of snippets in vscode (code template)

Panel panel of UI

Unity get component

django连接数据库报错,这是什么原因

Romance of programmers on Valentine's Day

Recherche de mots pour leetcode (solution rétrospective)

Unity3d learning notes
随机推荐
Database under unity
PostgreSQL surpasses mysql, and the salary of "the best programming language in the world" is low
Django reports an error when connecting to the database. What is the reason
Unity get component
Kali 2018 full image download
Reverse one-way linked list of interview questions
使用Room数据库报警告: Schema export directory is not provided to the annotation processor so we cannot expor
3dsmax2018 common operations and some shortcut keys of editable polygons
FVP和Juno平台的Memory Layout介绍
Unity find the coordinates of a point on the circle
How much do you know about 3DMAX rendering skills and HDRI light sources? Dry goods sharing
Bucket sort
Count sort
National teacher qualification examination in the first half of 2022
Cocos create Jiugongge pictures
Optimization scheme of win10 virtual machine cluster
Heap sort summary
A three-dimensional button
Cocos2dx screen adaptation
被舆论盯上的蔚来,何时再次“起高楼”?