统计一个数字在排序数组中出现的次数。
示例 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 34. 在排序数组中查找元素的第一个和最后一个位置(二分查找)
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
target
的数字class Solution {
public:
int search(vector<int>& nums, int target) {
int i = binarysearchFirstTarget(nums,target);
if(i == -1)
return 0;
int count = 0, k;
for(k = i; k < nums.size(); ++k)
if(nums[k] == target)
count++;
return count;
}
int binarysearchFirstTarget(vector<int>& nums, int& target)
{
int l = 0, r = nums.size()-1, mid;
while(l <= r)
{
mid = l +((r-l)>>1);
if(nums[mid] < target)
l = mid+1;
else if(nums[mid] > target)
r = mid-1;
else
{
if(mid == 0 || nums[mid-1] != nums[mid])
return mid;
else
r = mid-1;
}
}
return -1;
}
};