题目
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].
思路
这种查找类的题目,而且原数组还有序,基本的思路就是二分查找,找到相等的值,再从两边扩散查找
代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l=0,r=nums.size()-1,mid;
while(l<=r)
{
mid = (l+r)/2;
if(nums[mid]>target)
r = mid-1;
else if(nums[mid]<target)
l=mid+1;
else
break;
}
if(l<=r)
{
int temp = mid;
while(mid>=0)
{
if(nums[mid]==target)
mid--;
else
break;
}
while(temp<=nums.size()-1)
{
if(nums[temp]==target)
temp++;
else
break;
}
return {mid+1,temp-1};
}
else
return {-1,-1};
}
};