【二分查找】LCR 172. 统计目标成绩的出现次数
发布时间:2024年01月20日
LCR 172. 统计目标成绩的出现次数
解题思路
- 二分查找
- 计算Target的左边界 计算右边界
- 右边界 - 左边界 + 1
class Solution {
public int countTarget(int[] scores, int target) {
if(right_bound(scores,target) == -1){
return 0;
}
return right_bound(scores,target) - left_bound(scores,target) + 1;
}
int left_bound(int[] nums,int target){
int left = 0;
int right= nums.length - 1;
while(left <= right){
int mid = (right - left) / 2 + left;
if(nums[mid] < target){
left = mid + 1;
}else if(nums[mid] > target){
right = mid - 1;
}else if(nums[mid] == target){
right = mid - 1;
}
}
if(left >= nums.length ||nums[left] != target){
return -1;
}
return left;
}
int right_bound(int[] nums,int target){
int left = 0;
int right= nums.length - 1;
while(left <= right){
int mid = (right - left) / 2 + left;
if(nums[mid] < target){
left = mid + 1;
}else if(nums[mid] > target){
right = mid - 1;
}else if(nums[mid] == target){
left = mid + 1;
}
}
if(right < 0 ||nums[right] != target){
return -1;
}
return right;
}
}
文章来源:https://blog.csdn.net/qq_44653420/article/details/135713259
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!