力扣--LCR 172.统计目标成绩的出现次数
题目
某班级考试成绩按非严格递增顺序记录于整数数组 scores,请返回目标成绩 target 的出现次数。
示例 1:
输入: scores = [2, 2, 3, 4, 4, 4, 5, 6, 6, 8], target = 4
输出: 3
示例 2:
输入: scores = [1, 2, 3, 5, 7, 9], target = 6
输出: 0
提示:
0 <= scores.length <= 105
-109 <= scores[i] <= 109
scores 是一个非递减数组
-109 <= target <= 109
因为是有序数组,所以只要找到目标成绩的第一个小标和最后一个小标相减即可。
代码
class Solution {
public int countTarget(int[] scores, int target) {
if (scores == null || scores.length == 0) {
return 0;
}
int l = l(scores, target);
int r = r(scores, target);
if (l == -1 || r == -1) {
return 0;
}
return r - l + 1;
}
public int l(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
int m = 0;
int ans = -1;
while (l <= r) {
m = l + (r - l) / 2;
if (target <= nums[m]) {
ans = m;
r = m - 1;
} else {
l = m + 1;
}
}
if (ans != -1 && nums[ans] != target)
ans = -1;
return ans;
}
public int r(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
int m = 0;
int ans = -1;
while (l <= r) {
m = l + (r - l) / 2;
if (target >= nums[m]) {
ans = m;
l = m + 1;
} else {
r = m - 1;
}
}
if (ans != -1 && nums[ans] != target)
ans = -1;
return ans;
}
}