题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
- 只要找到重复数字的左边界。之后迭代判断即可。
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { if(!data.size()) return 0; int res = 0; int left = 0; int right = data.size()-1; while(left<right){ int mid = (left+right)/2; if(data[mid]==k){ right = mid; }else if(data[mid]<k){ left = mid + 1; }else{ right = mid; } } for(;left< data.size();left++){ if(data[left]==k) res++; } return res; } };
剑指Offer 文章被收录于专栏
剑指offer的解析结合