Idea: This
question is a typical dichotomous basic problem. The dichotomies I wrote here are divided into two types, which can be understood as finding the maximum value in the minimum range and finding the minimum value in the maximum range.
Code:
class Solution {
public:
int func_1(vector<int>& nums,int target){
int l = 0,r = nums.size()-1;
while(l<r){
int mid = (l+r) >> 1;
if(nums[mid] >= target) r = mid;
else l = mid+1;
}
if(nums[l]==target) return l ;
else return -1;
}
int func_2(vector<int>& nums,int target){
int l =0, r = nums.size()-1;
while(l<r){
int mid = (l+r+1)>>1;
if(nums[mid] <= target)
l =mid;
else
r =mid-1;
}
return l;
}
int search(vector<int>& nums, int target) {
if(nums.size()==0) return 0;
int idx = func_1(nums,target);
if(idx==-1) return 0;
int idy = func_2(nums,target);
return idy-idx+1;
}
};