题目描述
统计一个数字在排序数组中出现的次数。
public class Solution { public int GetNumberOfK(int [] array , int k) { if(array.length == 0)return 0; int num1 = getFirst(array, 0, array.length-1, k); int num2 = getLast(array, 0, array.length-1, k); if(num1 != -1 && num2 != -1) return num2 - num1 +1; return 0; } public int getFirst(int[] array, int l, int r, int k) { if(l>r)return -1; int mid = (l+r) >> 1; if(array[mid]<k)return getFirst(array, mid+1, r, k); else if(array[mid]>k)return getFirst(array, l, mid-1, k); else if((mid-1>=0) && (array[mid-1] == k)) return getFirst(array, l, mid-1, k); else return mid; } public int getLast(int[] array, int l, int r, int k) { int mid = (l+r) >>1; int len = array.length; while(l<=r) { if(array[mid]<k) l = mid+1; else if(array[mid]>k) r = mid-1; else if(mid+1<len && array[mid+1] == k) l = mid+1; else return mid; mid = (l+r)>>1; } return -1; } }