在 .NET 4.0+ 中,一个类SortedSet<T>
有一个方法叫做GetViewBetween(l, r)
,它返回树部分的接口视图,其中包含指定的两个值之间的所有值。鉴于SortedSet<T>
被实现为红黑树,我自然希望它能够运行在O(log N)
时间。 C++中类似的方法是std::set::lower_bound/upper_bound
,在 Java 中是TreeSet.headSet/tailSet
,并且它们是对数的。
然而,事实并非如此。以下代码运行时间为 32 秒,而等效代码O(log N)
的版本GetViewBetween
将使此代码在 1-2 秒内运行。
var s = new SortedSet<int>();
int n = 100000;
var rand = new Random(1000000007);
int sum = 0;
for (int i = 0; i < n; ++i) {
s.Add(rand.Next());
if (rand.Next() % 2 == 0) {
int l = rand.Next(int.MaxValue / 2 - 10);
int r = l + rand.Next(int.MaxValue / 2 - 10);
var t = s.GetViewBetween(l, r);
sum += t.Min;
}
}
Console.WriteLine(sum);
我使用反编译System.dlldotPeek这就是我得到的:
public TreeSubSet(SortedSet<T> Underlying, T Min, T Max, bool lowerBoundActive, bool upperBoundActive)
: base(Underlying.Comparer)
{
this.underlying = Underlying;
this.min = Min;
this.max = Max;
this.lBoundActive = lowerBoundActive;
this.uBoundActive = upperBoundActive;
this.root = this.underlying.FindRange(this.min, this.max, this.lBoundActive, this.uBoundActive);
this.count = 0;
this.version = -1;
this.VersionCheckImpl();
}
internal SortedSet<T>.Node FindRange(T from, T to, bool lowerBoundActive, bool upperBoundActive)
{
SortedSet<T>.Node node = this.root;
while (node != null)
{
if (lowerBoundActive && this.comparer.Compare(from, node.Item) > 0)
{
node = node.Right;
}
else
{
if (!upperBoundActive || this.comparer.Compare(to, node.Item) >= 0)
return node;
node = node.Left;
}
}
return (SortedSet<T>.Node) null;
}
private void VersionCheckImpl()
{
if (this.version == this.underlying.version)
return;
this.root = this.underlying.FindRange(this.min, this.max, this.lBoundActive, this.uBoundActive);
this.version = this.underlying.version;
this.count = 0;
base.InOrderTreeWalk((TreeWalkPredicate<T>) (n =>
{
SortedSet<T>.TreeSubSet temp_31 = this;
int temp_34 = temp_31.count + 1;
temp_31.count = temp_34;
return true;
}));
}
So, FindRange
显然是O(log N)
,但之后我们调用VersionCheckImpl
...它对找到的子树进行线性时间遍历,只是为了重新计算其节点!
- 为什么你需要一直进行这种遍历?
- 为什么 .NET 不包含
O(log N)
基于键分割树的方法,如 C++ 或 Java?这是really在很多情况下都有帮助。