根据SortedSet<T>.GetEnumerator
文档:
此方法是O(1)操作。
根据SortedDictionary<K, V>.GetEnumerator
文档:
此方法是O(log n)操作,其中n是计数。
考虑到SortedDictionary<K,V>
在内部被实现为SortedSet<KeyValuePair<K,V>
,这两个陈述是否都可以成立呢?我检查了SortedDictionary
类的GetEnumerator
代码-它直接使用SortedSet
的枚举器。我注意到SortedSet
的枚举器实现并且它似乎具有O(log n)的特性(这是代码):
public SortedSet<T>.Enumerator GetEnumerator()
{
return new SortedSet<T>.Enumerator(this);
}
//which calls this constructor:
internal Enumerator(SortedSet<T> set)
{
this.tree = set;
this.tree.VersionCheck();
this.version = this.tree.version;
this.stack = new Stack<SortedSet<T>.Node>(2 * SortedSet<T>.log2(set.Count + 1));
this.current = (SortedSet<T>.Node) null;
this.reverse = false;
this.siInfo = (SerializationInfo) null;
this.Intialize();
}
private void Intialize()
{
this.current = (SortedSet<T>.Node) null;
SortedSet<T>.Node node1 = this.tree.root;
while (node1 != null)
{
SortedSet<T>.Node node2 = this.reverse ? node1.Right : node1.Left;
SortedSet<T>.Node node3 = this.reverse ? node1.Left : node1.Right;
if (this.tree.IsWithinRange(node1.Item))
{
this.stack.Push(node1);
node1 = node2;
}
else
node1 = node2 == null || !this.tree.IsWithinRange(node2.Item) ? node3 : node2;
}
}
这难道不意味着文档有误,SortedSet<T>.GetEnumerator
的时间复杂度是O(log n)吗? 关于GetEnumerator
调用的性能并没有太多说明,只是确保我理解正确。
SortedSet<KeyValuePair<K,V>>
。它不会调用枚举器 log n 次。此外,我的问题不是 SortedDictionary 是 O(logn),而是 SortedSet 是 O(1)。这就是为什么我只发布了 SortedSet 枚举器的代码。从代码来看,它似乎不是 O(1),而是 O(logn)。 - nawfal