先用二分查找定位到目标值k的位置,再以k的位置索引为原点向两边搜索k的个数😁
public class Solution { public int GetNumberOfK(int [] array , int k) { if (array.length == 0) return 0; return this.binarySearch(array,0,array.length-1,k); } private static int binarySearch(int[] array,int left,int right,int k) { if (left > right) return 0; int mid = (left + right) / 2; int minVal = array[mid]; int count = 0; if (k < minVal) { return binarySearch(array,left,mid-1,k); } else if (k > minVal) { return binarySearch(array,mid+1,right,k); } else { // 当k==minVal时,再向左和向右寻找k的个数 int leftMid = mid; int rightMid = mid+1; // 向左(前提:使用”&&“运算符保证下标不越界) while (leftMid >= 0 && k == array[leftMid]) { count++; leftMid--; } // 向右 while (rightMid <= array.length-1 && k == array[rightMid] ) { count++; rightMid++; } return count; } } }