二分查找写法
牛客网题目:统计一个数字在排序数组中出现的次数。
public class Solution { public int GetNumberOfK(int [] array , int k) { int length = array.length; if(length == 0){ return 0; } int firstK = getFirstK(array, k, 0, length-1); int lastK = getLastK(array, k, 0, length-1); return lastK - firstK + 1; } //递归写法 private int getFirstK(int [] array , int k, int start, int end){ if(start > end){ return start; } int mid = (end-start)/2 + start; if(array[mid] < k){ return getFirstK(array, k, mid+1, end); }else { return getFirstK(array, k, start, mid -1); } } //循环写法 private int getLastK(int [] array , int k, int start, int end){ int length = array.length; while(start <= end){ int mid = (end-start)/2 + start; if(array[mid] > k){ end = mid-1; }else if(array[mid] <= k){ start = mid+1; } } return end; } }
二分查找的套路链接:https://www.cnblogs.com/luoxn28/p/5767571.html
https://www.zhihu.com/question/36132386/answer/530313852
在代码的世界尽情的翱翔吧!