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]
.
Analysis:
From the question, we may know it need binary search.
The idea is to search twince one for left range bound, one for right range bound.
Java
public int[] searchRange(int[] A, int target) {
int[] result = new int[2];
result[0] = getBoundRange(A, 0, A.length-1, target, true);
result[1] = getBoundRange(A, 0, A.length-1, target, false);
return result;
}
public int getBoundRange(int[]A, int l, int r, int target, boolean left){
if(l>r) return -1;
else{
int m = (l+r)/2;
if(A[m]==target){
if(left){
if(m==0 || A[m-1]target) {
return getBoundRange(A, l, m-1, target, left);
}else {
return getBoundRange(A, m+1, r, target, left);
}
}
}
Another solution:
public int[] searchRange(int[] A, int target) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
if(A[0]>target || A[A.length-1]=0&&A[low]==target){
low--;
}
result[0]=low+1;
while(hightarget){
high = mid-1;
}else {
low = mid+1;
}
}
return result;
}
c++
int searchTarget(int A[], int start, int end, int target){
if(start > end)
return -1;
else{
int mid = (start+end)/2;
if(A[mid] == target) return mid;
if(A[mid]> target)
return searchTarget(A,start,mid-1,target);
if(A[mid] searchRange(int A[], int n, int target) {
vector result;
int index = searchTarget(A,0,n-1,target);
if(index == -1){
result.push_back(-1);
result.push_back(-1);
return result;
}
else{
int ls = index;
while(ls>0 && A[index] == A[ls-1]) ls--;
int rs = index;
while(rs