如何找到在一个TreeSet的元素的索引?索引、元素、TreeSet

2023-09-10 23:59:42 作者:时光巷陌

我使用了一个 TreeSet的<整数GT; ,我想很简单,喜欢找一些在设置索引。有没有一个很好的办法做到这一点,实际上是利用二叉树的O(日志(N))的复杂性?

I'm using a TreeSet<Integer> and I'd quite simply like to find the index of a number in the set. Is there a nice way to do this that actually makes use of the O(log(n)) complexity of binary trees?

(如果没有,我该怎么办,而且没有人知道为什么不呢?我很好奇,为什么这样一类会不会像搜索功能包含在Java的。)

(If not, what should I do, and does anyone know why not? I'm curious why such a class would be included in Java without something like a search function.)

推荐答案

由于@Yrlec指出 set.headSet(元素).size 将返回0,虽然没有该元素在集。所以,我们最好检查:

As @Yrlec points out set.headSet(element).size will returns 0 though there is no this element in the set. So we'd better check:

 return set.contains(element)? set.headSet(element).size(): -1;

下面是一个测试用例,显示问题:

Here is a test case to show the problem:

public static void main(String args[]){
    TreeSet<Integer> set = new TreeSet<>();
    set.add(4);
    set.add(2);
    set.add(3);
    set.add(1);

    System.out.println(set.headSet(1).size());//0
    System.out.println(set.headSet(2).size());//1
    System.out.println(set.headSet(3).size());//2
    System.out.println(set.headSet(4).size());//3
    System.out.println(set.headSet(-1).size());//0!!Caution!,retusn 0 though it does not exits

}
 
精彩推荐
图片推荐