题目描述
统计一个数字在排序数组中出现的次数。
#include <iostream>
#include <vector>
using namespace std;
int GetNumberOfK(vector<int> data ,int k){
int len=data.size();
if(len==0) return 0;
int low=0;
int high=len-1;
int mid;
while(low<high){
mid=(low+high)/2;
if(data[mid]==k)
break;
else{
if(data[mid]<k){
low=mid+1;
}else{
high=mid-1;
}
}
}
mid=(low+high)/2;
if(data[mid]!=k) return 0;
int sum=1;
int i=mid-1;
while(i>=0&&data[i]==k){
sum++;
i--;
}
i=mid+1;
while(i<len&&data[i]==k){
sum++;
i++;
}
return sum;
}
int main(){
//int a[10]={1,2,3,3,3,4,5,6,8,8};
int a[6]={3,3,3,3,4,5};
vector<int> vec(a,a+6);
cout<<GetNumberOfK(vec,3)<<endl;
system("pause");
}