统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
=====================================================================================================
分析:这里还是要使用二分查找。
(1)根据二分查找,我们先判断中间的数是不是目标数target:如果是,则在其左右检索,看还有没有相等的数,并统计个数;
(2)如果不是,就分别在左右进行二分查找。
(3)代码
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length;
int count = 0; //计数
while(left<right){
int mid = (left+right)/2;
if(nums[mid]==target){ //相等
int l = mid;
int r = mid;
while(l>=0&&nums[l]==target){
l--;
count++;
}
while(r<nums.length&&nums[r]==target){
r++;
count++;
}
return count-1; //多统计了一次
}else if(nums[mid]>target){ //中间值大,查找区间在左侧
right = mid;
}else{
left=mid+1;
}
}
return count;
}
}
参考:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof