# （算法）二分查找的搜索区间

1、直接遍历数组，复杂度O(n)

2、二分查找

## 代码：

```#include<iostream>
#include<vector>

using namespace std;

int searchLeft(const vector<int> &A,int left,int right,int target){
int first=left;
int last=right;
int mid=-1;
while(first<=last){
mid=first+((last-first)>>1);
if(A[mid]==target){
if(mid>left && A[mid-1]==target)
last=mid-1;
else
return mid;
}
else if(A[mid]<target)
first=mid+1;
else
last=mid-1;
}
return mid;
}

int searchRight(const vector<int> &A,int left,int right,int target){
int first=left;
int last=right;
int mid=-1;
while(first<=last){
mid=first+((last-first)>>1);
if(A[mid]==target){
if(mid<right && A[mid+1]==target)
first=mid+1;
else
return mid;
}
else if(A[mid]<target)
first=mid+1;
else
last=mid-1;
}
return mid;
}

void searchRange(const vector<int> &A,int left,int right,int target,int &start,int &end){
start=searchLeft(A,left,right,target);
end=searchRight(A,left,right,target);
}

int main(){
int n;
int start=-1;
int end=-1;
int target;

while(cin>>n){
vector<int> num(n);
for(int i=0;i<n;i++)
cin>>num[i];
cin>>target;
searchRange(num,0,n-1,target,start,end);
cout<<start<<" "<<end<<endl;
}
return 0;
}```

原文作者：AndyJee
原文地址: https://www.cnblogs.com/AndyJee/p/4827426.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。