Description:统计一个数字在排序数组中出现的次数。
public class Solution {
public int GetNumberOfK(int[] a, int k) {
int index = binarySearch(a, k);
if (index == -1) return 0;
int cnt = 0;
int left = index;
int right = index + 1;
while (left >= 0 && a[left--] == a[index])
cnt++;
while (right < a.length && a[right++] == a[index])
cnt++;
return cnt;
}
public int binarySearch(int[] a, int k) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < k)
low = mid + 1;
else if (midVal > k)
high = mid - 1;
else
return mid;
}
return -1;
}
}