class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//if (!A) return NULL;
int l=0;
int r=n;
int position=-1;
vector<int> res;
while (l<=r) {
int mid=(l+r)/2;
if (target==A[mid]) {
position=mid;
break;
}else if (target>A[mid]) {
l=mid+1;
}else {
r=mid-1;
}
}
if (position==-1) {
res.push_back(-1);
res.push_back(-1);
return res;
}
int left=position;
while (A[left-1]==target) {
if(left>0) {
left--;
}else{
break;
}
}
res.push_back(left);
while (A[position+1]==target) {
if(position<n-1) {
position++;
}else {
break;
}
}
//position--;
res.push_back(position);
return res;
}
};Search for a Range
搜索目标范围算法
最新推荐文章于 2022-03-08 23:18:06 发布
本文介绍了一个C++实现的算法,该算法用于在一个整数数组中查找特定目标值首次和末次出现的位置。通过二分查找确定目标值的位置,并进一步向左右两侧遍历以找出其出现的范围。
3241

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



