题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param numsLen int nums数组长度 * @param k int整型 * @return int整型 */ int Numbers(int* nums, int mid, int numsLen) { int ret = 1; for (int i = mid-1; i >= 0; i--) { if (nums[i] == nums[mid]) { ret++; } else { break; } } for (int i = mid+1; i < numsLen; i++) { if (nums[i] == nums[mid]) { ret++; } else { break; } } return ret; } int GetNumberOfK(int* nums, int numsLen, int k ) { // write code here int left = 0; int right = numsLen - 1; int mid = 0; while(left <= right) { mid = (left + right) / 2; if (nums[mid] < k) { left = mid + 1; } else if (nums[mid] > k) { right = mid - 1; } else { return Numbers(nums, mid, numsLen); } } return 0; }