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 m;
else return getBoundRange(A, l, m-1, target, left);
}else {
if(m==A.length-1 || target<A[m+1]) return m;
else return getBoundRange(A, m+1, r, target, left);
}
}
else if (A[m]>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]<target) return result;
int low = 0;
int high = A.length-1;
while(low<=high){
int mid = low+(high-low)/2;
if(A[mid]==target){
high = mid;
low = mid;
while(low>=0&&A[low]==target){
low--;
}
result[0]=low+1;
while(high<A.length&&A[high]==target){
high++;
}
result[1] = high-1;
return result;
}else if(A[mid]>target){
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]<target)
return searchTarget(A,mid+1,end,target);
}
}
vector<int> searchRange(int A[], int n, int target) {
vector<int> 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<n-1 && A[index] == A[rs+1]) rs++;
result.clear();
result.push_back(ls);
result.push_back(rs);
}
return result;
}