37、数字在排序数组中出现的次数
一、题目
统计一个数字在排序数组中出现的次数。
二、解法
1 public class Solution { 2 public int GetNumberOfK(int [] array , int k) { 3 if(array == null || array.length == 0) 4 return 0; 5 int first = GetFirst(array,k,0,array.length-1); 6 int last = GetLast(array,k,0,array.length-1); 7 if(first == -1 || last == -1) 8 return 0; 9 return last-first+1; 10 } 11 //获取第一个 12 public int GetFirst(int[] array,int k, int start, int end){ 13 while(start <= end){ 14 int mid = (start+end)/2; 15 if(k < array[mid]) 16 end = mid-1; 17 else if(k > array[mid]) 18 start = mid+1; 19 else{//当相等的时候 并左边一个不等于k 或者是第一个 20 if(mid == 0 || (mid > 0 && array[mid-1] != k)) 21 return mid; 22 else 23 end = mid-1; 24 } 25 } 26 return -1; 27 } 28 //获取最后一个 29 public int GetLast(int[] array,int k, int start, int end){ 30 while(start<=end){ 31 int mid = (start+end)/2; 32 if(k < array[mid]) 33 end = mid-1; 34 else if(k > array[mid]) 35 start = mid+1; 36 else{ 37 //当相等的时候,下标等于最后一个 或者右边一个不等于k 38 if(mid == array.length-1 || 39 (mid < array.length-1 && array[mid+1] != k)) 40 return mid; 41 else 42 start = mid+1; 43 } 44 } 45 return -1; 46 } 47 }