class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> res(2,-1);
int start=0;
int end=n-1;
while(start<end) {
int mid=(start+end)/2;
if (A[mid]>target) {
end=mid-1;
}else if (A[mid]<target) {
start=mid+1;
}
else {
end=mid;
}
}
if (A[start]==target) {
res[0]=start;
}else {
return res;
}
end=n;
while(start<end) {
int mid=(start+end)/2;
if (A[mid]>target) {
end=mid;
}else if (A[mid]<target) {
start=mid+1;
}
else {
start=mid+1;
}
}
res[1]=end-1;
return res;
}
};
Search for a Range
最新推荐文章于 2022-03-08 23:18:06 发布
本文介绍了一种用于在已排序数组中高效查找特定元素范围的算法。通过二分查找技术,该算法能够在对数组进行一次遍历的情况下确定目标值的起始和结束位置,从而实现快速定位。
3246

被折叠的 条评论
为什么被折叠?



