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,
1:考虑特殊情况; 2:二分查找分别找到目标值的最左边的索引和最右边的索引。
vector<int> searchRange(int A[], int n, int target) {
vector<int> result;
if(A == NULL || n <= 0 )
{
result.push_back(-1);
result.push_back(-1);
return result;
}
int left = findLeftIndex(A, 0, n - 1, target);
if(left == -1)
{
result.push_back(-1);
result.push_back(-1);
return result;
}
else
{
result.push_back(left);
int right = findRightIndex(A, 0, n - 1 , target);
result.push_back(right);
return result;
}
}
int findLeftIndex(int A[], int start, int end, int target)
{
while(start <= end)
{
int middle = (start + end) / 2;
if(A[middle] >= target)
{
end = middle - 1;
}
else
{
start = middle + 1;
}
}
if(A[start] == target)
{
return start;
}
else
{
return -1;
}
}
int findRightIndex(int A[], int start, int end, int target)
{
while(start <= end)
{
int middle = (start + end) / 2;
if(A[middle] <= target)
{
start = middle + 1;
}
else
{
end = middle - 1;
}
}
if(A[end] == target)
{
return end;
}
else
{
return -1;
}
}