【二分查找算法】
1.朴素二分模板
溢出风险
当计算中间点的下标时:
int mid = (left + right)/2;
一般情况下是这样的
但是,在加法中,有可能left + right > INT_MAX,此时就溢出了。
为了防止溢出,可以这样计算:
int mid = left + (right - left)/2;
while(left <= right) //细节1
{
int mid = left + (right - left) / 2; //细节2
if(...)
right = mid - 1;
else if(...)
left = mid + 1;
else
return ...;
}
2.查找左端点和右端点的细节以及模板
查找左端点的二分模板
1.while(left < right)
{
int mid = left + (right - left )/2;
if(...) mid = left + 1;
else mid = right;
}
查找右端点的二分模板
2.while(left < right)
{
int mid = left + (right - left +1)/2;
if(...) mid = left;
else mid = right -1;
}
具体题型:
vector<int> searchRange(vector<int>& nums, int t)
{
if(nums.size() == 0)
return {-1,-1};
int i = -1,j = -1;
//1.先找左端点
int left = 0,right = nums.size()-1;
while(left < right) // 细节1
{
//选求出靠左的中点方法
int mid = left + (right-left)/2; // 细节2
//细节3
//在不合法区间
if(nums[mid] < t) left = mid+1;
//在合法区间
else right = mid;
}
//循环结束条件一定是left = right;
if(nums[right] == t) // 或 nums[right] == t
i = left;
//2.找右端点
left = 0;
right = nums.size()-1;
while(left < right) //细节1
{
//选求出靠右的中点方法
int mid = left + (right-left+1)/2; //细节2
//细节3
//在合法区间
if(nums[mid] <= t) left = mid;
//在不合法区间
else right = mid-1;
}
//循环结束条件一定是left = right;
if(nums[left] == t) //或 nums[right] == t
j = left;
//如果i,j的值不变,说明没有此区间
return {i,j};
}
};
原文地址:https://blog.csdn.net/w2915w/article/details/142418175
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!