题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
二分法查找
注意:
1、升序--->二分
2、先找到一个数,然后向两边找
3、注意保存mid的值,方便作为反向查找的起点
4、多次统计注意区分
代码
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int l = 0; int r = data.size()-1; int res = 0; while(l<=r){ int mid = (l+r)/2; if(data[mid] == k){ int tmp_mid = mid; while(mid>=0 && data[mid]==k){ res++; mid--; } while(tmp_mid<=data.size()-1 && data[tmp_mid]==k){ res++; tmp_mid++; } return res-1; } else if(data[mid]>k){ r = mid-1; } else{ l = mid+1; } } return 0; } };