剑指 Offer 53 - I. 在排序数组中查找数字 I
题目描述
统计一个数字在排序数组中出现的次数。
示例1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
代码实现
class Solution {
public:
int search(vector<int>& nums, int target) {
int i, j, m;
int left, right;
// Search the left boundary
i = 0; j = nums.size() - 1;
while(i <= j) {
m = (i + j) / 2;
if(nums[m] < target)
i = m + 1;
else
j = m - 1;
}
left = j;
// Search the right boundary
i = 0; j = nums.size() - 1;
while(i <= j) {
m = (i + j) / 2;
if(nums[m] > target)
j = m - 1;
else
i = m + 1;
}
right = i;
return right - left - 1;
}
};