https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
class Solution {
public int search(int[] nums, int target) {
int leftId = binarySearch(nums, target, true);
int rightId = binarySearch(nums, target, false) - 1;
//因为nums是一个非递减数组,leftID到rightId的数都是target,所以是rightId - leftId + 1
if (leftId <= rightId && rightId < nums.length && nums[leftId] == target && nums[rightId] == target)
return rightId - leftId + 1;
return 0;
}
//二分查找,当lower为true时,找第一个大于等于target数组元素的下标,lower为false时,找第一个大于target数组元素的下标
public int binarySearch (int[] nums, int target, boolean lower) {
int left = 0, right = nums.length - 1, ans = nums.length;
while (left <= right) {
int mid = (left + right) / 2;
//lower为false时,只考虑nums[mid]>target的情况
//lower为true时,两者都考虑,但后者的范围更大
if (nums[mid] > target || (lower && nums[mid] >= target)) {
//因为是要找到第一个,所以不断地逼近
right = mid - 1;
ans = mid;
}
else {
//逼近
left = mid + 1;
}
}
return ans;
}
}