简体   繁体   English

TreeSet的最坏情况时间复杂度是多少?

[英]What's the worst-case time complexity of TreeSet?

It is stated here that 这里说明了

TreeSet has a log(n) time complexity guarantuee for add()/remove()/contains(). TreeSet具有add()/ remove()/ contains()的log(n)时间复杂度保证。

But TreeSet uses a binary search tree and in the worst case, binary search trees can have O(n) height. TreeSet使用二叉搜索树,在最坏的情况下,二叉搜索树可以具有O(n)高度。 How is the log(n) complexity "guaranteed"? log(n)复杂性如何“保证”?

The implementation rebalances the tree upon inserts. 实现在插入时重新平衡树。

The O(lg n) time bound for insert is guaranteed by the official documentation . insert的O(lg n)时间由官方文档保证。 This should not come as a surprise: A classic way to implement sets is as some sort of self-balancing binary search tree . 这不应该是一个惊喜:实现集合的经典方法是某种自平衡二叉搜索树

Java libraries are publicly available, so let's go see for ourselves. Java库是公开的,所以让我们自己去看看。 TreeSet can be found, eg, here . 例如,可以在这里找到TreeSet It is implemented in terms of TreeMap , which is in turn here . 它是根据TreeMap实现的,而TreeMap又是在这里实现的 As @Don Roby points out, the underlying data structure is a Red-Black tree. 正如@Don Roby指出的那样,底层数据结构是红黑树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM