问题描述:
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]
根据以上问题描述,算法复杂度要求不超过O(log N),而且数组是升序排序的,因而不妨从二分查找的角度来进行考虑。所以很容易可以想到,先使用二分法寻找到目标值所在的坐标,然后从找到的坐标往左右两边开始做寻找,从而找到给定目标值的开始坐标和结束坐标。
代码如下:
class Solution {
public:
vector
searchRange(vector
& nums, int target) {
int len = nums.size();
vector
result;
int startIndex = findIndex(nums,target,0,len-1);
if(startIndex!=-1)
{
int endIndex = startIndex;
while((endIndex)<(len-1)&&nums[startIndex]==nums[endIndex+1])
{
endIndex++;
}
while((startIndex-1)>=0&&nums[startIndex]==nums[startIndex-1])
{
startIndex--;
}
result.push_back(startIndex);
result.push_back(endIndex);
return result;
}
result.push_back(-1);
result.push_back(-1);
return result;
}
int findIndex(vector
& nums,int target,int start,int end)
{
if((end-start)<0)
return -1;
int index = (end+start)/2;
if(nums[index]==target)
return index;
if(nums[index]
target) return findIndex(nums,target,start,index-1); } };
运行时间:9ms