思路:
二分法,分别找出第一个和最后一个k出现的位置。相减 加一
#include <stdio.h>
//获取第一个K的位置
int getFirstK (int k,int *numbers,int start,int end){ if(start > end){
return -;
} int middle = (start + end) / ;
int middleData = numbers[middle]; if(middleData < k){
start = middle + ;
}else if(middleData > k){
end = middle - ;
}else{
if(middle> && numbers[middle-]!=k //注意这个if
|| middle==){
return middle;
}else{
end = middle -;
}
} getFirstK(k,numbers,start,end);
}
//获取最后一个K的位置
int getLastK (int k,int *numbers,int start,int end){ if(start > end){
return -;
} int middle = (start + end) / ;
int middleData = numbers[middle]; if(middleData < k){
start = middle + ;
}else if(middleData > k){
end = middle - ;
}else{
if(middle<end && numbers[middle+]!=k
|| middle==end){
return middle;
}else{
start = middle + ;
}
} getLastK(k,numbers,start,end);
} //得到k 在numbers中的个数
int getNumberOfK(int k, int* numbers,int length){
if(numbers == NULL || length <= ){
return ;
} int last = getLastK(k, numbers,, length-);
int first = getFirstK(k, numbers,, length-); if(last == - || first == -){
return ;
}
return last - first + ;
} int main(){ int numbers1[] = {,,,,,,,,,,,,,,,,,,,};
printf("%d\n",getNumberOfK(,numbers1,)); int numbers2[] = {,,,,,,,,,};
printf("%d\n",getNumberOfK(,numbers2,)); int* numbers3 = NULL;
printf("%d\n",getNumberOfK(,numbers3,)); }