Find dichotomy position k back then forward traversal.
Or find the first and last position k k then subtract binary search is used only when the first judge to find k around k is not k is then not return until it is determined to continue to narrow the scope of this is on the edge
public class Solution { public int GetNumberOfK(int [] array , int k) { if(array.length == 0 || array == null){ return 0; } int result=find(array,0,array.length-1,k); int count=0; if(result >= 0){ count =1; int i=result,j=result; while (i>=1 && array[i] == array[i-1]){ count ++; i --; } while (j < array.length-1 && array[j] == array[j+1]){ count ++; j ++; } } return count; } private int find(int[] array, int left, int right, int k) { int mid=0; while (left <= right){ mid=(left+right)>>1; if(array[mid] < k){ left=mid+1; }else if (array[mid] > k){ right = mid-1; }else { return mid; } } return -1; } }
Binary algorithm to find: