力扣,https://leetcode.cn/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/description/
二分查找,边界问题
自己的方法,其实不太好
class Solution {
public int countTarget(int[] scores, int target) {
if (scores.length == 0) {
return 0;
}
int[] inxArray = new int[]{-1, -1};
binarySearch(0, scores.length - 1, scores, target, inxArray);
if (inxArray[0] == -1 && inxArray[1] == -1) {
return 0;
}
return inxArray[1] - inxArray[0] + 1;
}
public void binarySearch(int start, int end, int[] scores, int target, int[] inxArray) {
if (start > end) {
return;
}
int mid = start + (end - start) / 2;
if (scores[mid] == target) {
inxArray[0] = mid;
inxArray[1] = mid;
while (inxArray[0] - 1 >= 0 && scores[inxArray[0] - 1] == target) {
inxArray[0] -= 1;
}
while (inxArray[1] + 1 < scores.length && scores[inxArray[1] + 1] == target) {
inxArray[1] += 1;
}
return;
} else if (scores[mid] < target) {
start = mid + 1;
binarySearch(start, end, scores, target, inxArray);
} else {
end = mid - 1;
binarySearch(start, end, scores, target, inxArray);
}
}
}