题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
怎么我的二分那么***
public class Solution { public int GetNumberOfK(int [] array , int k) { int n = array.length; if(n == 0){ return 0; } int count = 0; int l = binarySearch(array,k); if(l != -1){ count = 1; } while(l > 0){ if(array[--l] == k){ count++; } } int r = binarySearch(array,k); while(r < n-1){ if(array[++r] == k){ count++; } } return count; } public int binarySearch(int[] arr,int k){ int left = 0,right = arr.length-1; while(left <= right){ int mid = left + (right-left)/2; if(k == arr[mid]){ return mid; }else if(k > arr[mid]){ left = mid+1; }else{ right = mid-1; } } return -1; } }