Search for a Range
Given an array of integers sorted in ascending order, 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].
Solution: Using Binary Search
The key is to find the first index of target, and then find the first index of target+1.
int searchRangeUtil(vector<int> A, int left, int right, int target) {
while (left < right) {
int mid = left + (right - left)/2;
if (A[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
vector<int> searchRange(vector<int> &A, int target) {
int left = searchRangeUtil(A, 0, A.size(), target);
int right = searchRangeUtil(A, left, A.size(), target+1);
if (left > right-1) return {-1, -1};
return {left, right-1};
}