题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
/** * * @param data int整型一维数组 * @param dataLen int data数组长度 * @param k int整型 * @return int整型 */ int GetNumberOfK(int* data, int dataLen, int k ) { int left = 0; int right = dataLen - 1; int mid = 0; int num = 0; int flag = 0; while(left <= right) { if(k>data[right]) break; mid = left + (right - left) / 2; if(data[mid] > k) { right = mid - 1; } else if(data[mid] < k) { left = mid + 1; } else { flag = mid - 1; while(data[flag]==k && flag >= 0) { ++num; flag--; } while (data[mid]==k && mid < dataLen) { ++num; mid++; } break; } } return num; // write code here }