题目
![撤销:Ctrl/Command + Z重做:Ctrl/Command + Y加粗:Ctrl/Command + B斜体:Ctrl/Command + I标题:Ctrl/Command + Shift + H无序列表:Ctrl/Command + Shift + U有序列表:Ctrl/Command + Shift + O检查列表:Ctrl/Command + Shift + C插入代码:Ctrl/Command + Shift + K插入链接:Ctrl/Command + Shift + L插入图片:Ctrl/Command + Shift + G查找:Ctrl/Command + F替换:Ctrl/Command + G](https://i-blog.csdnimg.cn/blog_migrate/f48def99bb91903675c21ac84eb5bd85.png#pic_center)
代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int>answer(2);
if (nums.size()==0)
{
answer[0]=-1;
answer[1]=-1;
return answer;
}
int left=0,right=nums.size()-1;
int MAX=-1,MIN=nums.size();
doit(nums,target,answer,left,right,MIN,MAX);
if (MIN==nums.size()) MIN=-1;
answer[0]=MIN;
answer[1]=MAX;
return answer;
}
void doit(vector<int>& nums, int target,vector<int>& answer,int left,int right,int &MIN,int &MAX)
{
if (left>right) return;
if (left==right)
{
if (nums[left]==target)
{
MAX=max(MAX,left);
MIN=min(MIN,left);
}
else
{
MIN=-1;
}
return ;
}
int mid=left+(right-left)/2;
if (nums[mid]==target)
{
MAX=max(MAX,mid);
MIN=min(MIN,mid);
if ((mid+1<=nums.size()-1)&&(mid-1>=0)&&nums[mid-1]==target&&nums[mid+1]==target)
{
cout<<"ok3"<<endl;
doit(nums,target,answer,mid+1,right,MIN,MAX);
doit(nums,target,answer,left,mid-1,MIN,MAX);
}
else if ((mid+1<=nums.size()-1)&&nums[mid+1]==target)
{
cout<<"ok1"<<endl;
if (mid-1>=0&&nums[mid-1]!=target)
doit(nums,target,answer,mid+1,right,MIN,MAX);
else if (mid-1<0)
doit(nums,target,answer,mid+1,right,MIN,MAX);
}
else if ((mid-1>=0)&&nums[mid-1]==target)
{
cout<<"ok2"<<endl;
if (mid+1<=nums.size()-1&&nums[mid+1]!=target)
doit(nums,target,answer,left,mid-1,MIN,MAX);
else if (mid+1>=nums.size())
doit(nums,target,answer,left,mid-1,MIN,MAX);
}
}
else if (nums[mid]>target) doit(nums,target,answer,left,mid-1,MIN,MAX);
else doit(nums,target,answer,mid+1,right,MIN,MAX);
}
};