zoukankan      html  css  js  c++  java
  • C++ STL中的lower_bound,upper_bound使用小结

    首先记得 #include < algorithm >

    在vector中使用

    lower_bound作用

    非递减序列中 找到 第一个大于或者等于 某个元素的位置,如果找得到,返回相应的迭代器,否则,返回范围中的尾迭代器。

    使用示例

    vector<int> nums = { 3,2,4,1,5 };
    sort(nums.begin(), nums.end());
    auto iter = lower_bound(nums.begin(), nums.end(), 1);
    cout << iter - nums.begin() << endl;
    

    upper_bound作用

    非递减序列中 找到 第一个大于 某个元素的位置,如果找得到,返回相应的迭代器,否则,返回范围中的尾迭代器。

    使用示例

    vector<int> nums = { 3,2,4,1,5 };
    sort(nums.begin(), nums.end());
    auto iter = upper_bound(nums.begin(), nums.end(), 1);
    cout << iter - nums.begin() << endl;
    

    在map中使用

    由于map本身就是按照key进行排序的(默认就是升序),所以,在map中可以直接使用。在map中使用时,lower_bound和upper_bound的功能和之前是一样的。

    使用示例

    map<int, int> m;
    m.insert({ 2, 4 });
    m.insert({ 1, 3 });
    m.insert({ 3, 7 });
    m.insert({ 5, 5 });
    m.insert({ 4, 6 });
    
    auto iter = m.lower_bound(3);//auto iter = m.upper_bound(3);
    cout << iter->first << " , " << iter->second << endl;
    

    总结

    注意,lower_bound和upper_bound的时间复杂度都是O(logn)

    leetcode题目

    436. Find Right Interval

    代码

    class Solution {
    public:
        vector<int> findRightInterval(vector<vector<int>>& intervals) {
            vector<int> res;
            map<int, int> m;
            for(int i = 0; i < intervals.size(); i++) m[intervals[i][0]] = i;
    
            for(auto e : intervals){
                auto it = m.lower_bound(e[1]);
                if(it != m.end()) res.push_back(-1);
                else res.push_back(it->second);
            }
    
            return res;
        }
    };
    
    只有0和1的世界是简单的
  • 相关阅读:
    url向视图函数传递参数
    创建django项目
    进度百分比
    【转藏】Makefile学习
    IT人的自我导向型学习:学习的4个层次
    SZ第二次找工作--笔试汇总
    正则表达式 (re包)——python(快餐)
    Python-快速学习
    Vim的使用
    Vim Python
  • 原文地址:https://www.cnblogs.com/nullxjx/p/15143353.html
Copyright © 2011-2022 走看看