题目
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].
在有序数组中,寻找指定值的起始位置,未找到返回[-1, -1]。
思路
采用两边二分查找,第一遍查找开始下标,第二遍查找结束下标,时间复杂度为O(logn)
代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result(2, -1);
if(nums.size() == 0)
return result;
int ll = 0, lr = nums.size() - 1, mid;
while(ll <= lr){
mid = (ll + lr) / 2;
if(nums[mid] < target)
ll = mid + 1;
else
lr = mid - 1;
}
int rl = 0, rr = nums.size() - 1;
while(rl <= rr){
mid = (rl + rr) / 2;
if(nums[mid] <= target)
rl = mid + 1;
else
rr = mid - 1;
}
if(ll <= rr){
result[0] = ll;
result[1] = rr;
}
return result;
}
};