class Solution {
public:
int findleft(vector<int>& nums, int target) {
int n = nums.size();
int left = 0, right=n;
while(left<right) {
int mid = left + (right-left)/2;
int m = nums[mid];
if(m<target){
left = mid+1;
} else if(m>target) {
right = mid;
} else if(m==target) {
right = mid;
}
}
if(left<n&&nums[left]==target) return left;
else return -1;
}
int findright(vector<int>& nums, int target) {
int n = nums.size();
int left = 0, right=n;
while(left<right) {
int mid = left + (right-left)/2;
int m = nums[mid];
if(m<target){
left = mid+1;
} else if(m>target) {
right = mid;
} else if(m==target) {
left = mid+1;
}
}
// if(left<n&&nums[left]==target) return left;
if(right>0&&nums[right-1]==target) return right-1;
else return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {
return {findleft(nums, target),findright(nums, target)};
}
};
左闭右闭
class Solution {
public:
int findleft(vector<int>& nums, int target) {
int n = nums.size();
int left = 0, right=n-1;
while(left<=right) {
int mid = left + (right-left)/2;
int m = nums[mid];
if(m<target){
left = mid+1;
} else if(m>target) {
right = mid-1;
} else if(m==target) {
right = mid-1;
}
}
if(left<n&&nums[left]==target) return left;
else return -1;
}
int findright(vector<int>& nums, int target) {
int n = nums.size();
int left = 0, right=n-1;
while(left<=right) {
int mid = left + (right-left)/2;
int m = nums[mid];
if(m<target){
left = mid+1;
} else if(m>target) {
right = mid-1;
} else if(m==target) {
left = mid+1;
}
}
// if(left<n&&nums[left]==target) return left;
if(right>=0&&nums[right]==target) return right;
else return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {
return {findleft(nums, target),findright(nums, target)};
}
};