题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
public class Solution {
public int GetNumberOfK(int [] array , int k) {
// 左闭右闭
int left = 0;
int right = array.length - 1;
// 因为是闭区间 不加等于号会漏掉一个元素
while (left <= right){
int mid = left + (right - left)/2;
if(array[mid] == k){
while (array[left] != k || array[right] != k){
if (array[left] != k) left ++;
else right --;
}
return right - left + 1;
}else if(array[mid] < k){
left = mid + 1;
}else{
right = mid - 1;
}
}
return 0;
}
}