思路:用两分二次查找即可,第一次查找确定key第一次出现的位置,第二次查找确定key最后一次出现的位置。
int fun(vector<int> &arr,int size,int key)
{
if(arr.empty())
return 0;
int left =0;
int right=size-1;
int mid;
while(left<=right){
mid=left+(right-left)>>1;
if(arr[mid]==key){
if(mid-1>=0&&arr[mid-1]==key)
right=mid-1;
else
break;
}else if(arr[mid]>key)
right=mid-1;
else
left=mid+1;
}
if(left>right)
return 0;
int tmp=mid;
left =mid;
right=size-1;
while(left<=right){
mid=left+(right-left)>>1;
if(arr[mid]==key){
if(mid+1<size&&arr[mid+1]==key)
left=mid+1;
else
break;
}else if(arr[mid]>key)
right=mid-1;
else
left=mid+1;
}
return mid-tmp+1;
}