剑指offer 38_统计数组中k出现的个数
思路:
二分法,分别找出第一个和最后一个k出现的位置。相减 加一
#include <stdio.h>
//获取第一个K的位置 int getFirstK (int k,int *numbers,int start,int end){ if(start > end){ return -1; } int middle = (start + end) / 2; int middleData = numbers[middle]; if(middleData < k){ start = middle + 1; }else if(middleData > k){ end = middle - 1; }else{ if(middle>0 && numbers[middle-1]!=k //注意这个if || middle==0){ return middle; }else{ end = middle -1; } } getFirstK(k,numbers,start,end); }
//获取最后一个K的位置 int getLastK (int k,int *numbers,int start,int end){ if(start > end){ return -1; } int middle = (start + end) / 2; int middleData = numbers[middle]; if(middleData < k){ start = middle + 1; }else if(middleData > k){ end = middle - 1; }else{ if(middle<end && numbers[middle+1]!=k || middle==end){ return middle; }else{ start = middle + 1; } } getLastK(k,numbers,start,end); } //得到k 在numbers中的个数 int getNumberOfK(int k, int* numbers,int length){ if(numbers == NULL || length <= 0){ return 0; } int last = getLastK(k, numbers,0, length-1); int first = getFirstK(k, numbers,0, length-1); if(last == -1 || first == -1){ return 0; } return last - first + 1; } int main(){ int numbers1[20] = {1,1,1,2,3,3,3,3,3,3,3,3,4,5,6,7,66,7787,8888,9999}; printf("%d\n",getNumberOfK(3,numbers1,20)); int numbers2[10] = {1,2,2,2,2,5,6,7,8,9}; printf("%d\n",getNumberOfK(3,numbers2,10)); int* numbers3 = NULL; printf("%d\n",getNumberOfK(3,numbers3,10)); }