如何查找TreeSet中元素的索引?
我正在使用 TreeSet
并且我只想找到集合中数字的索引。有没有一种很好的方法来做到这一点,实际上利用了二叉树的 O(log(n)) 复杂度?
(如果没有,我应该做什么,有谁知道为什么不?我很好奇为什么这样的类会包含在 Java 中,而没有搜索功能之类的东西。)
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?
(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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我研究了 TreeSet 及其接口一段时间,我发现获取元素索引的最佳方法是:
headSet(element)
返回 TreeSet 的子TreeSet
元素小于其参数,因此该集合的大小将是相关元素的索引。确实是一个奇怪的解决方案。I poked around TreeSet and its interfaces for a while, and the best way I found to get the index of an element is:
headSet(element)
returns the sub-TreeSet
of elements less than its argument, so the size of this set will be the index of the element in question. A strange solution indeed.正如 @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:Here is a test case to show the problem:
https://github.com/geniot/indexed-tree-map
我有同样的问题。于是我就拿了java.util.TreeMap的源码,写了IndexedTreeMap。它实现了我自己的IndexedNavigableMap:
该实现基于红黑树中节点权重发生变化时的更新。权重是给定节点下的子节点数量加一 - self。例如,当一棵树向左旋转时:
updateWeight 只是将权重更新到根:
当我们需要通过索引查找元素时,这里是使用权重的实现:
查找键的索引也非常方便:
您可以在 https://github.com/geniot/indexed-tree 找到这项工作的结果-地图
https://github.com/geniot/indexed-tree-map
I had the same problem. So I took the source code of java.util.TreeMap and wrote IndexedTreeMap. It implements my own IndexedNavigableMap:
The implementation is based on updating node weights in the red-black tree when it is changed. Weight is the number of child nodes beneath a given node, plus one - self. For example when a tree is rotated to the left:
updateWeight simply updates weights up to the root:
And when we need to find the element by index here is the implementation that uses weights:
Also comes in very handy finding the index of a key:
You can find the result of this work at https://github.com/geniot/indexed-tree-map
Java 中的
TreeSet
类无法查找集合中数字的索引。为此,您必须提供自己的实现 - 它是底层的红黑树,并且可以对其进行扩充以支持索引操作。看看“算法导论”的“增强数据结构”一章中的OS-RANK
过程,这正是您所要求的。The
TreeSet
class in Java doesn't have the ability to find the index of a number in the set. For that, you'd have to provide your own implementation - it is a Red-Black tree under the hood, and it can be augmented to support the index operation. Take a look at theOS-RANK
procedure in the chapter "Augmenting Data Structures" of "Introduction to Algorithms", it's precisely what you're asking for.这里显示我的函数:
//FUNCTION FOR GIVE A STRING POSITION INTO TREESET
here show my function:
//FUNCTION FOR GIVE A STRING POSITION INTO TREESET