当前位置:网站首页>Leetcode (34) -- find the first and last positions of elements in a sorted array
Leetcode (34) -- find the first and last positions of elements in a sorted array
2022-07-01 23:23:00 【SmileGuy17】
Leetcode(34)—— Find the first and last positions of the elements in the sort array
subject
Give you an array of integers in non decreasing order n u m s nums nums, And a target value t a r g e t target target. Please find out the start position and end position of the given target value in the array .
If the target value does not exist in the array t a r g e t target target, return [ − 1 , − 1 ] [-1, -1] [−1,−1].
You must design and implement a time complexity of O ( log n ) O(\log n) O(logn) The algorithm to 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]
Tips :
- 0 0 0 <= nums.length <= 1 0 5 10^5 105
- − 1 0 9 -10^9 −109 <= nums[i] <= 1 0 9 10^9 109
- nums It's a Non decreasing group
- − 1 0 9 -10^9 −109 <= target <= 1 0 9 10^9 109
Answer key
Method 1 : Brute force
Ideas
The intuitive idea must be to traverse from front to back . Record the first and last encounter with two variables target \textit{target} target The subscript , But the time complexity of this method is O ( n ) O(n) O(n), The condition of ascending array arrangement is not used .
Code implementation
My own :
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans(2, -1);
int l = 0, r = nums.size()-1;
while(l <= r){
if(nums[l] == target){
ans[0] = l;
break;
}
l++;
}
if(l > r) return ans;
while(l <= r){
if(nums[r] == target){
ans[1] = r;
break;
}
r--;
}
return ans;
}
};
Complexity analysis
Time complexity : O ( n ) O(n) O(n), among n n n It's an array nums The length of
Spatial complexity : O ( 1 ) O(1) O(1)
Method 2 : Two points search
Ideas
Because the array has been sorted , So the whole array is monotonically increasing , We can Use dichotomy to speed up the search process .
consider target \textit{target} target Start and end positions , In fact, what we're looking for is in the array 「 The first is equal to target \textit{target} target The location of 」( Write it down as leftIdx \textit{leftIdx} leftIdx) and 「 The first one is greater than target \textit{target} target Minus one 」( Write it down as rightIdx \textit{rightIdx} rightIdx).
Binary search , seek leftIdx \textit{leftIdx} leftIdx That is to find the first greater than or equal to in the array target \textit{target} target The subscript , seek rightIdx \textit{rightIdx} rightIdx That is to find the first greater than in the array target \textit{target} target The subscript , Then subtract the subscript by one . The judgment conditions of the two are different , For code reuse , We define binarySearch(nums, target, lower) It means that nums \textit{nums} nums Binary search in array target \textit{target} target The location of , If lower \textit{lower} lower by t r u e \rm true true, Then find the first one greater than or equal to target \textit{target} target The subscript , Otherwise, find the first greater than target \textit{target} target The subscript .
Last , because target \textit{target} target May not exist in the array , So we need to recheck the two subscripts we get leftIdx \textit{leftIdx} leftIdx and rightIdx \textit{rightIdx} rightIdx, See if they meet the requirements , If the conditions are met, return [ leftIdx , rightIdx ] [\textit{leftIdx},\textit{rightIdx}] [leftIdx,rightIdx], Go back if you don't agree [ − 1 , − 1 ] [-1,-1] [−1,−1].
Code implementation
Leetcode Official explanation :
class Solution {
public:
int binarySearch(vector<int>& nums, int target, bool lower) {
int left = 0, right = (int)nums.size() - 1, ans = (int)nums.size();
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > target || (lower && nums[mid] >= target)) {
right = mid - 1;
ans = mid;
} else {
left = mid + 1;
}
}
return ans;
}
vector<int> searchRange(vector<int>& nums, int target) {
int leftIdx = binarySearch(nums, target, true);
int rightIdx = binarySearch(nums, target, false) - 1;
if (leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target) {
return vector<int>{
leftIdx, rightIdx};
}
return vector<int>{
-1, -1};
}
};
Complexity analysis
Time complexity : O ( log n ) O(\log n) O(logn), among n n n Is the length of the array . The time complexity of binary search is O ( log n ) O(\log n) O(logn), It will be executed twice , So the total time complexity is O ( log n ) O(\log n) O(logn)
Spatial complexity : O ( 1 ) O(1) O(1)
边栏推荐
- 建模和影视后期有什么关联?
- Advanced skills of testers: a guide to the application of unit test reports
- 问题随记 —— /usr/bin/perl is needed by MySQL-server-5.1.73-1.glibc23.x86_64
- 2022 safety officer-c certificate examination question simulation examination question bank and simulation examination
- 硅谷产品实战学习感触
- 2022安全员-C证考试题模拟考试题库及模拟考试
- Contents of other parts of the map
- 物联网应用技术专业是属于什么类
- 马赛克后挡板是什么?
- Jerry's question about long press boot detection [chapter]
猜你喜欢

Redis data types and application scenarios

2022 examination questions and online simulation examination for safety management personnel of hazardous chemical business units
![[applet] realize the left and right [sliding] list through the scroll view component](/img/18/b1b4e9923782856143721dad84cbab.png)
[applet] realize the left and right [sliding] list through the scroll view component

The digital summit is popular, and city chain technology has triggered a new round of business transformation

Distance measurement - Hamming distance

问题随记 —— file /usr/share/mysql/charsets/README from install of MySQL-server-5.1.73-1.glibc23.x86_64 c

软件架构的本质

Redis数据类型和应用场景

【小程序】通过scroll-view组件实现左右【滑动】列表
![Compare the version number [double pointer to intercept the string you want]](/img/19/4f858ffdc1281d6b8b18a996467f10.png)
Compare the version number [double pointer to intercept the string you want]
随机推荐
认识线程
openresty 负载均衡
Zhongang Mining: it has inherent advantages to develop the characteristic chemical industry dominated by fluorine chemical industry
[micro service sentinel] sentinelresourceaspect details
Matplotlib common settings
What is the relationship between modeling and later film and television?
通过Go语言创建CA与签发证书
Summary of "performance testing" of software testing, novice will know the knowledge points on the road
软件架构的本质
Aaai22 | structural tagging and interaction modeling: a "slim" network for graph classification
from pip._internal.cli.main import main ModuleNotFoundError: No module named ‘pip‘
typescript枚举
攻防演习防御体系构建之第三篇之建立实战化的安全体系
MT manager test skiing Adventure
Jerry's burning of upper version materials requires [chapter]
Treatment of insufficient space in the root partition of armbain system
win 10 mstsc连接 RemoteApp
SWT/ANR问题--SWT 导致 kernel fuse deadlock
vim给目录加颜色
Jielizhi, production line assembly link [chapter]