Is there a Java function similar to C++'s PBDS order_of_key?

跟風遠走 提交于 2020-08-26 05:52:52

问题


In C++ we can use __gnu_pbds i.e. Policy based data structure. See the following code.

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

typedef tree<int, null_type, less<int>, rb_tree_tag,
        tree_order_statistics_node_update> PBDS;


int main()
{
        PBDS st;
        st.insert(1);
        st.insert(3);
        st.insert(4);
        st.insert(10);
        st.insert(15);
        for(int i=0;i<st.size();i++)
        {
           cout<<i<<" "<< *st.find_by_order(i) <<endl;
        } 
       cout<<st.order_of_key(5)<<endl; // 3
}

It has two important functionalities.

  1. find_by_order(k) : which returns an iterator so we can access it's index in PBDS set.
  2. order_of_key(k) : which return number of elements less than k.

Both the functions runs in O(logn) time. I want to use them in java. As these functions runs in logarithmic time Java TreeSet would be best match. for find_by_order(k) I have to convert TreeSet into a List to access its index. In TreeSet there are methods like higher() and lower() which return at least greater / at least smaller element. But I want the count of numbers less than k. So is it possible to do it in java ?

Help me figure it out. If I'm wrong at some point of time then let me know. Is their way to do it using java 8 streams ? orElse using Collection Framework ?

thanks✌️

来源:https://stackoverflow.com/questions/62356532/is-there-a-java-function-similar-to-cs-pbds-order-of-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!