如何在TreeSet中找到元素的索引? [英] How to find the index of an element in a TreeSet?

查看:33
本文介绍了如何在TreeSet中找到元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TreeSet 并且我只想在集合中找到一个数字的索引.有没有一种很好的方法来做到这一点,它实际上利用了二叉树的 O(log(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(element).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,returns 0 though it does not exist!

}

这篇关于如何在TreeSet中找到元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆