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]
.
(1)using binary search:
class Solution{
public:
vector<int> searchRange(vector<int> A, int target) {
int n = A.size();
int i = 0, j = n - 1;
vector<int> ret(2, -1);
// Search for the left one
while (i < j)
{
int mid = (i + j) /2;
if (A[mid] < target) i = mid + 1;
else j = mid;
}
if (A[i]!=target) return ret;
else ret[0] = i;
// Search for the right one
j = n-1; // We don't have to set i to 0 the second time.
while (i < j)
{
int mid = (i + j) /2 + 1; // Make mid biased to the right
if (A[mid] > target) j = mid - 1;
else i = mid; // So that this won't make the search range stuck.
}
ret[1] = j;
return ret;
}
};
(2) using STL lower_bound and upper_bound
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto lit=lower_bound(nums.begin(),nums.end(),target);
auto rit=upper_bound(nums.begin(),nums.end(),target);
--rit;
if(*lit!=target||(*rit)!=target)
return {-1,-1};
return {lit-nums.begin(),rit-nums.begin()};
}
};