题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
二分法查找,
public class Solution { public int GetNumberOfK(int [] array , int k) { if(array==null ||array.length==0) return 0; if(k<array[0]||k>array[array.length-1]) return 0; int left=0,right=array.length-1; int count=0,mid=0; while(left<=right){ mid =(left+right)/2; if(array[mid]>k) right=mid-1; else if(array[mid]<k) left=mid+1; else{//相等 count++; break; } } left=mid-1; right=mid+1; while(left>=0 && array[left]==k ) { count++; left--; } while( right<array.length && array[right]==k) { count++; right++; } return count; } }