Search for a Range Total accepted:21480 Total submissions:78454 My Submissions
Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O (log n).
If the target is not a found in the array, return [-1,-1].
For example,
Given [5, 7, 7, 8, 8, ten] and target value 8,
return [3, 4].
Test instructions: In a well-ordered array, look for the starting subscript and end subscript for a given value
Idea: two-point search
First use Lower_bound to find the starting subscript
and use Upper_bound to find the end subscript.
Lower_bound and Upper_bound Implementation see STL Source code Analysis
Complexity: Time O (log n) space O (1)
vector<int> searchrange (int a[], int n, int target) {
int l = distance (A, lower_bound (a, a + N, target));
int u = Distance (A, upper_bound (a, a + N, target));
vector<int> Res;
if (a[l]! = target) {
res.push_back ( -1);
Res.push_back ( -1);
} else{
Res.push_back (l);
Res.push_back (u-1);
}
return res;
}