Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
思路并不复杂,就是先用二分查找找到其中一个target,然后再往左右找到target的边缘。找边缘的方法跟二分查找仍然是一样的,只是切半的条件变成相等,或者不等(往左边找则是小于,往右边找则是大于)。或者 如果我们不寻找那个元素先,而是直接相等的时候也向一个方向继续夹逼,如果向右夹逼,最后就会停在右边界,而向左夹逼则会停在左边界,如此用停下来的两个边界就可以知道结果了,只需要两次二分查找。
C++实现代码:
#include<iostream> #include<vector> #include<set> using namespace std; class Solution { public: vector<int> searchRange(int A[], int n, int target) { if(n==0) return vector<int>{-1,-1}; int mid; int left=0; int right=n-1; int ll=-1; int rr=-1; while(left<=right) { mid=(left+right)/2; if(A[mid]<=target) { left=mid+1; } else right=mid-1; } if(A[right]==target) rr=right; left=0; right=n-1; while(left<=right) { mid=(left+right)/2; if(A[mid]>=target) right=mid-1; else left=mid+1; } if(A[left]==target) ll=left; return vector<int>{ll,rr}; } }; int main() { Solution s; int arr[6]={5}; vector<int> result=s.searchRange(arr,1,1); for(auto a:result) cout<<a<<" "; cout<<endl; }