栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【STL】——lower

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【STL】——lower

lower_bound和upper_bound

两个函数来源于algorithm库中

  • 未重载比较函数
    lower_bound是利用二分找出数组或者容器中第一个大于等于val的值对应的迭代器,而upper_bound是利用二分法找出数组或者容器中第一个大于val的值对应的迭代器。
    在STL源码中,两者的比较函数均为less<>,其中lower_bound的比较函数,二分的mid在前,val在后,此时可解释为:寻找第一个使得关系mid

*重载比较函数后
lower_bound是找出第一个不满足比较函数的关系的迭代器,而upper_bound找出第一个满足比较函数关系的迭代器。
此处可以通过leetcode一个二分题目说明。其中对这个二分问题,分别重载了两个函数的比较函数,从而达到了二分的目的。值得注意的是,lower_bound与upper_bound中val位置的不同,其中lower_bound的val位置在后,而upper_bound的val位置在后。

算法实现

class Solution {
public:
    int minEatingSpeed(vector& piles, int h) {
        int left = 1;
        int right = *max_element(piles.begin(), piles.end());
        vector ret_vec(right - left + 1);
        int k = -1;
        for (int i = left; i <= right; ++i)
            ret_vec[++k] = i;

        //int ret = *lower_bound(ret_vec.begin(), ret_vec.end(), h, [&](const int b, const int h) {
        //    int ret_b = 0;
        //    for (int pile : piles) {
        //        ret_b += (pile + b - 1) / b;
        //    }
        //    return h < ret_b;
        //    });

         int ret = *upper_bound(ret_vec.begin(), ret_vec.end(), h, [&](const int h, const int b){
             long ret_b = 0;
             for (int pile : piles) {
                 ret_b += (long)(pile + b - 1) / b;
             }
             return h >= ret_b;
         });
        return ret;
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/971627.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号