剑指Offer_37 发表于 2017-12-04 | 分类于 剑指Offer 题目统计一个数字在排序数组中出现的次数。 解题思路二分搜索法 12345678910111213141516171819202122232425262728293031323334353637public class Solution { public int GetNumberOfK(int [] array , int k) { if(array == null || array.length == 0){ return 0; } int lo = 0; int hi = array.length-1; int mid = 0; int cnt = 0; while(lo <= hi){ mid = (hi + lo) >> 1; if(array[mid] < k){ lo = mid + 1; } else if(array[mid] > k){ hi = mid - 1; } else{ cnt = 1; break; } } if(cnt == 0){ return 0; } int i = mid - 1; int j = mid + 1; while(i >= 0 && array[i--] == k) { ++cnt; } while(j < array.length && array[j++] == k) { ++cnt; } return cnt; }}