二分查找问题
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left(0),right=nums.size()-1,mid,b,p;
int end=right;
vector<int> ret(2,-1);
if(end<0) return ret;
while(1)
{
mid=(left+right)/2;
if(left>(right-2))//结束条件
{
if(nums[left]==target)
{
ret[0]=ret[1]=left;
if(nums[right]==target)
{
ret[1]=right;
}
}else if(nums[right]==target)
{
ret[0]=ret[1]=right;
}
return ret;
}
if(nums[mid]==target)
{
ret[0]=ret[1]=mid;
b=mid;
while(1)
{
p=(b+left)/2;
if(left>(b-2))
{
if(nums[left]==target)
{
ret[0]=left;
}else if(nums[b]==target)
{
ret[0]=b;
}
break;
}
if(nums[p]==target&&(!p||nums[p-1]!=target))
{
ret[0]=p;
break;
}else if(nums[p]!=target)
{
left=p;
}else{
b=p;
}
}
b=mid;
while(1)
{
p=(b+right)/2;
if(b>(right-2))
{
if(nums[right]==target)
{
ret[1]=right;
}else if(nums[b]==target)
{
ret[1]=b;
}
break;
}
if(nums[p]==target&&((p==end)||nums[p+1]!=target))
{
ret[1]=p;
break;
}else if(nums[p]!=target)
{
right=p;
}else{
b=p;
}
}
return ret;
}else if(nums[mid]<target)
{
left=mid;
}else{
right=mid;
}
}
}
};