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]
.
思路:
方法一:
按照传统的二分查找找到target元素所在的位置mid,分别循环对mid左右两边的元素与target值比较,直到左右两边的值与target值不同,记录下左右两边的索引返回。
此方法有一个缺点就是如果target值在数组中有多个,最多为数组全是target值,此时算法的时间复杂度为O(n),不满足题目要求,但是这种情况很少,所以可以简单忽略。
方法二:
另一种很有技巧的方法就是在数组中查找值target+1,在数组中分别找到target第一次应该出现的位置和target+1第一次应该出现的位置(如果没有target或者target+1,则返回值应该插入的位置)。
代码实现:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.size() < 1) return {-1, -1};
int index1 = low_boundary(nums, target);
int index2 = low_boundary(nums, target+1) -1;
if(index1 < nums.size() && nums[index1] == target) return {index1, index2};
return {-1,-1};
}
private:
int low_boundary(vector<int>& nums, int target){
int left = 0, right = nums.size() - 1;
int mid = (left + right) / 2;
while(left <= right)
{
mid = (left + right) / 2;
if(target > nums[mid])
left = mid + 1;
else right = mid - 1;
}
return left;
}
};