题目:
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].
思路:本题和Leetcode – 33. Search in Rotated Sorted Array思路相似,先用二分查找找到一个target的index,然后想两边扩展即可。
- 二分查找找到一个target的下标mid;
- 以mid为中心,向前查找;
- 以mid为中心,向后查找。
C++代码如下:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret;
if (nums.empty())
return {-1,-1};
int l = 0, r = nums.size() - 1;
int mid, lb, rb;
while (l <= r)
{
mid = (l + r) / 2;
if (nums[mid] == target)
break;
else if (nums[mid] < target)
l = mid + 1;
else
r = mid - 1;
}
if (l > r)
return {-1, -1};
lb = mid;
while (nums[lb-1] == target && lb > 0)
lb--;
ret.push_back(lb);
rb = mid;
while (nums[rb+1] == target && rb < nums.size()-1)
rb++;
ret.push_back(rb);
return ret;
}