精髓:
- 确定搜索区间是[ , ], 还是[ , )
- 准确切换mid
- 左右边界,正确返回candidate index
class Solution {
public:
int countTarget(vector<int>& scores, int target) {
const int left_bound = FindLeftBound(scores, target);
const int right_bound = FindRightBound(scores, target);
if(left_bound == -1){
return 0;
}
return right_bound - left_bound +1;
}
int FindLeftBound(const vector<int>& nums, int target){
int left = 0;
int right = nums.size(); // [ )
while(left < right){
int mid = left + (right - left) /2;
if(nums[mid] == target){
right = mid;
}
else if(nums[mid] > target){
right = mid;
}
else if (nums[mid] < target){
left = mid+1;
}
}
int candidate_index = left;
return candidate_index < nums.size() && nums[candidate_index] == target ? candidate_index : -1;
}
int FindRightBound(const vector<int>& nums, int target){
int left = 0;
int right = nums.size(); // [ )
while(left < right){
int mid = left + (right - left) /2;
if(nums[mid] == target){
left = mid+1;
}
else if(nums[mid] > target){
right = mid;
}
else if (nums[mid] < target){
left = mid+1;
}
}
const int candidate_index = right - 1;
return candidate_index >=0 && nums[candidate_index] == target ? candidate_index : -1;
}
};