📌  相关文章
📜  在C ++中为有序集实现upper_bound()和lower_bound()

📅  最后修改于: 2021-06-01 02:18:25             🧑  作者: Mango

先决条件:有序集和GNU C++ PBDS
给定有序集合和键K ,任务是在C++中找到集合中元素K的上限和下限。如果该元素不存在或无法计算两个范围,则打印-1

例子:

方法:

  • upper_bound(): upper_bound(key)函数返回的元素正好大于传入参数中的key。
  • lower_bound(): lower_bound(key)函数返回与参数中传递的key等效的元素。如果键不存在于有序集合中,则函数应返回大于参数的元素。
  • 为了实现upper_bound和lower_bound函数,可使用order_of_key()函数找到元素的索引(如果存在于作为参数传递的有序集中)。
  • 现在,可以通过简单比较存在于此索引处的元素来找到下限和上限。

下面是lower_bound()和upper_bound()的实现:

CPP
// C++ program to implement the
// lower_bound() and upper_bound()
// using Ordered Set
 
#include 
#include 
#include 
using namespace __gnu_pbds;
using namespace std;
 
// Ordered Set Tree
typedef tree, rb_tree_tag,
             tree_order_statistics_node_update>
    ordered_set;
 
ordered_set set1;
 
// Function that returns the lower bound
// of the element
int lower_bound(int x)
{
    // Finding the position of the element
    int pos = set1.order_of_key(x);
 
    // If the element is not present in the set
    if (pos == set1.size())
    {
        return -1;
    }
 
    // Finding the element at the position
    else
    {
        int element = *(set1.find_by_order(pos));
 
        return element;
    }
}
 
// Function that returns the upper bound
// of the element
int upper_bound(int x)
{
    // Finding the position of the element
    int pos = set1.order_of_key(x + 1);
 
    // If the element is not present
    if (pos == set1.size())
    {
        return -1;
    }
 
    // Finding the element at the position
    else
    {
        int element = *(set1.find_by_order(pos));
 
        return element;
    }
}
 
// Function to print Upper
// and Lower bound of K
// in Ordered Set
void printBound(int K)
{
 
    cout << "Lower Bound of " << K << ": " << lower_bound(K)
         << endl;
    cout << "Upper Bound of " << K << ": " << upper_bound(K)
         << endl;
}
 
// Driver's Code
int main()
{
    set1.insert(10);
    set1.insert(20);
    set1.insert(30);
    set1.insert(40);
    set1.insert(50);
 
    int K = 30;
    printBound(K);
 
    K = 60;
    printBound(K);
 
    return 0;
}


输出
Lower Bound of 30: 30
Upper Bound of 30: 40
Lower Bound of 60: -1
Upper Bound of 60: -1

时间复杂度: O(log N)

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”