题目:
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].
Solution:
思路:看到O(log(n))。改进的二分查找可满足。
注释很详细,思路都在代码里。
vector<int> searchRange(vector<int>& nums, int target)
{
int n = nums.size();
int left = 0;
int right = n-1;
int mid = 0;
vector<int> indexs;
if(n == 0) //数目为0返回[-1,-1]
{
indexs.push_back(-1);
indexs.push_back(-1);
return indexs;
}
Binary_Search(nums,target,left,right,indexs);//改进的二分查找
if(indexs.size() == 0)//返回的下标数组不存在下标,返回[-1,-1]
{
indexs.push_back(-1);
indexs.push_back(-1);
return indexs;
}
else if(indexs.size() == 1)//返回单个下标,说明只有一个,那就返回[index[0],index[0]]。
{
indexs.push_back(indexs[0]);
return indexs;
}
else
{
sort(indexs.begin(),indexs.end()); //如果没有,先排个序,STL里快排O(log(n))。符合条件,找出第一个和最后一个即可
vector<int> temp_index;
temp_index.push_back(indexs[0]);
temp_index.push_back(indexs[indexs.size()-1]);
return temp_index;
}
}
void Binary_Search(vector<int>& nums,int target,int left,int right,vector<int>& indexs)
{
if(left <= right)
{
int mid = (left+right)/2;
if(nums[mid] == target)//找到了,则加进去,但是可能不止一个,所以还需继续二分
{
indexs.push_back(mid);
Binary_Search(nums,target,left,mid-1,indexs);
Binary_Search(nums,target,mid+1,right,indexs);
}
else if(target < nums[mid])
Binary_Search(nums,target,left,mid-1,indexs);
else
Binary_Search(nums,target,mid+1,right,indexs);
}
}