题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
//二分法查找 int GetNumberOfK(int* data, int dataLen, int k ) { int i=0; int count = 0;//记录k所出现的次数 int left = 0;//数组最左边的数 int ret = 0;//保护mid int right = dataLen-1;//数组最右边的数 int mid = dataLen / 2;//中间数 if(k==0) { return count; } while(left<right) { if(data[mid]<k) { left = mid; mid = (left + right) / 2; } if(data[mid]>k) { right = mid; mid = (left + right) / 2; } left++; right--; } if(data[mid] == k) { count++; ret = mid; while(data[mid-1] == k) { count++; mid--; } mid = ret; while(data[mid+1] == k) { count++; mid++; } } printf("%d",count); return count; }