统计一个数字在排序数组中出现的次数。
示例1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
解题思路
二分查找:
因为输入时有序数组,优先想到在该数组中查找target,二分法显然为时间最优解。如果target大于1个,则剩余的必定在其他区间,同样可以使用二分查找法来计数。
public int search(int[] nums, int target) {
return helper(nums, target, 0, nums.length - 1);
}
public int helper(int[] nums, int target, int low, int high) {
int count = 0;
if (low <= high) {
int mid = (high - low) / 2 + low;
if (nums[mid] == target) {
count++;
count+=helper(nums, target, low, mid - 1);
count+=helper(nums, target, mid + 1, high);
} else if (nums[mid] > target) {
count+=helper(nums, target, low, mid - 1);
} else {
count+=helper(nums, target, mid + 1, high);
}
}
return count;
}