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_index = -1;
int max_index = -1;
bool first_meet = true;
for (int i = 0; i < n-1; ++i) {
if (A[i] == target){
if (first_meet) {
min_index = i;
first_meet = false;
}
if (A[i+1] > A[i]) {
max_index = i;
}
}
}
if (A[n-1] == target) {
if (first_meet) {
min_index = n - 1;
}
max_index = n - 1;
}
return vector<int>({min_index, max_index});
}
};