剑指 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 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
解题思路
1)遍历,暴力解法,这里不再赘述
2) 递归二分查找
class Solution {
public static void main(String[] args) {
System.out.println(search(new int[]{5, 7, 7, 8, 8, 10}, 8));
}
public static int search(int[] nums, int target) {
return serachs(nums, 0, nums.length - 1, target);
}
public static int serachs(int[] nums, int left, int right, int target) {
int ans = 0;
if (left > right) {
return ans;
}
int mid = (right + left) / 2;
if (nums[mid] == target) {
ans++;
ans += serachs(nums, left, mid - 1, target);
ans += serachs(nums, mid + 1, right, target);
} else if (nums[mid] > target) {
ans += serachs(nums, left, mid - 1, target);
} else {
ans += serachs(nums, mid + 1, right, target);
}
return ans;
}
}