题目描述
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
代码实现
class Solution {
public int search(int[] nums, int target) {
if(nums == null || nums.length == 0){
return 0;
}
int first = helper(nums, target - 0.5);
int last = helper(nums, target + 0.5);
return last - first;
}
public int helper(int[] nums, double target){
int start = 0, end = nums.length - 1;
while(start <= end){
int mid = start + (end - start)/2;
if(nums[mid] < target) start = mid +1;
else end = mid -1;
}
return start;
}
}