二分查找 还写了半天。
right = mid-1 我直接写成了 right= mid。
还要考虑没有查找到的情况
public class Solution { public int GetNumberOfK(int [] array , int k) { int len = array.length; if(len ==0) return 0; int mid = -1; int left = 0; int right = len-1; while(left<=right){ mid = (left + right) /2; if(array[mid] > k){ right = mid-1; } else if( array[mid] < k){ left = mid+1; } else break; } if(array[mid]!=k){return 0;} while(mid>0 && array[mid] == array[mid-1]){mid--;} int res = 1; while(mid+1<array.length && array[mid] == array[mid+1]){mid++;res++;} return res; } }