我知道add,get等基本操作的时间复杂度是O(logn).但我没有找到lower()和更高()的细节.那么,Java中的TreeSet的lower()和更高()的时间复杂度是多少?
TreeSet由名为TreeMap的NavigableMap实现支持.在TreeSet上计算lower()时最终调用的代码是TreeMap上的lowerEntry().
/** * Returns the entry for the greatest key less than the specified key; if * no such entry exists (i.e., the least key in the Tree is greater than * the specified key), returns {@code null}. */ final EntrygetLowerEntry(K key) { Entry p = root; while (p != null) { int cmp = compare(key, p.key); if (cmp > 0) { if (p.right != null) p = p.right; else return p; } else { if (p.left != null) { p = p.left; } else { Entry parent = p.parent; Entry ch = p; while (parent != null && ch == parent.left) { ch = parent; parent = parent.parent; } return parent; } } } return null; }
查看此代码,看起来与while循环的每次迭代一样,每个分支返回或遍历树的一个级别.由于树图应具有log(n)
级别,因此整个方法具有O(log(n))
复杂性.