学习到一篇很好的博客 二分法的细节加细节 你真的应该搞懂!!! 详细的讲清了二分的边界问题,左右边界问题。
#include<bits/stdc++.h>
using namespace std;
int Left(vector<int>& nums, int target) {
int left = 0, right = nums.size();
int mid;
while(left < right) {
mid = left + (right - left) / 2;
// cout << left << " " <<right << " " << mid <<endl;
if(nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] == target) { // 收缩右边界 shrink right side
right = mid; // right缩小的方式与左闭右开的区间绑定 区间为[left, mid)已经将mid去除掉了 如果right=mid-1则会多去掉一个单位
} else { // 缩小右区间
right = mid;
}
}
return left;
}
int Right(vector<int>& nums, int target) {
int left = 0, right = nums.size();
int mid;
while(left < right) {
mid = left + (right - left) / 2;
// cout << left << " " <<right << " " << mid <<endl;
if(nums[mid] < target) { // 收缩左边界 shrink left side
left = mid + 1;
} else if (nums[mid] == target) { // 缩小左区间
left = mid + 1;
} else {
right = mid; // right缩小的方式与左闭右开的区间绑定
}
}
return left - 1;
}
int main()
{
int target;
cin >> target;
vector<int> vec = {1,2,2,2,3,3,3,3,4,4,5};
cout << Left(vec, target) << " " <<Right(vec, target);
return 0;
}