解题思路:二分查找
题解一
class Solution {
public int countTarget(int[] scores, int target) {
// 搜索右边界 right
int i = 0, j = scores.length - 1;
while(i <= j) {
int m = (i + j) / 2;
if(scores[m] <= target) i = m + 1;
else j = m - 1;
}
int right = i;
// 若数组中无 target ,则提前返回
if(j >= 0 && scores[j] != target) return 0;
// 搜索左边界 right
i = 0; j = scores.length - 1;
while(i <= j) {
int m = (i + j) / 2;
if(scores[m] < target) i = m + 1;
else j = m - 1;
}
int left = j;
return right - left - 1;
}
}
题解二(优化版)
class Solution {
public int countTarget(int[] scores, int target) {
return helper(scores, target) - helper(scores, target - 1);
}
int helper(int[] scores, int tar) {
int i = 0, j = scores.length - 1;
while(i <= j) {
int m = (i + j) / 2;
if(scores[m] <= tar) i = m + 1;
else j = m - 1;
}
return i;
}
}