题目要求:
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)
{
int left = -1;
int right = -1;
vector<int> res;
if(A == NULL || n <= 0)
{
res.push_back(left);
res.push_back(right);
return res;
}
left = FindLeftIndex(A, n, target);
right = FindRightIndex(A, n, target);
res.push_back(left);
res.push_back(right);
return res;
}
int FindLeftIndex(int A[], int n, int target)
{
int mid;
int low = 0, high = n - 1;
while(low <= high)
{
mid = low + ((high - low) >> 1);//防止溢出
if(A[mid] == target && (mid == 0 || A[mid - 1] != target))
return mid;
if(A[mid] >= target)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
int FindRightIndex(int A[], int n, int target)
{
int mid;
int low = 0, high = n - 1;
while(low <= high)
{
mid = low + ((high - low) >> 1);
if(A[mid] == target && (mid == (n - 1) || A[mid + 1] != target))
return mid;
if(A[mid] <= target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
};