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].
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
int min,max,mid;
int i, j;
min = 0;
max = n-1;
vector<int> result ;
if(A[0] > target|| A[n-1] <target)
{
result.push_back(-1);
result.push_back(-1);
return result ;
}
while(min <= max)
{
mid = min + (max - min)/2;
if(A[mid] == target)
break;
else if(A[mid] < target)
min = mid + 1;
else
max = mid - 1;
}
if( A[mid] == target ) {
i=j = mid;
while(i>=0 && A[i] == target)i-- ;
while(j<= n-1 && A[j] == target) j++ ;
i++;j--;
result.push_back(i);
result.push_back(j) ;
}else{
result.push_back(-1);
result.push_back(-1);
}
return result ;
}
};
--------------------------------------------------------------------天道酬勤!