题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
//二分查找然后左右找就可以了
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int mid,low,high;
int num=0;
high = array.length-1;
low = 0;
mid = (low + high) / 2;
while(high >= low){
if(array[mid] == k){
for(int i = mid;i<array.length;i++){
if(array[i] == k){
num++;
}
}
for(int i = mid;i>=0;i--){
if(array[i] == k){
num++;
}
}
return num-1;
}
if(array[mid] < k){
low = mid+1;
mid = (low+high) /2;
}
if(array[mid] > k){
high = mid-1;
mid = (low+high) /2;
}
}
return 0;
}
}