其他分享
首页 > 其他分享> > 认清二分法的细节

认清二分法的细节

作者:互联网

学习到一篇很好的博客 二分法的细节加细节 你真的应该搞懂!!! 详细的讲清了二分的边界问题,左右边界问题。

#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;
}

标签:right,cout,nums,int,认清,mid,二分法,细节,left
来源: https://www.cnblogs.com/fashow/p/15235058.html