【问题标题】:.NET equivalent of Java's TreeSet.floor & TreeSet.ceiling.NET 等效于 Java 的 TreeSet.floor 和 TreeSet.ceiling
【发布时间】:2018-09-05 07:56:41
【问题描述】:

例如,有一个包含一系列值的二叉搜索树。在添加新值之前,我需要检查它是否已经包含它“几乎重复”。我有 Java 解决方案,它简单地执行地板和天花板以及完成这项工作的进一步条件。

JAVA:给定一个TreeSetfloor()返回这个集合中小于或等于给定元素的最大元素; ceiling() 返回此集合中大于或等于给定元素的最小元素

TreeSet<Long> set = new TreeSet<>();

long l = (long)1;  // anything
Long floor = set.floor(l);
Long ceil = set.ceiling(l);

C#:最近的数据结构似乎是SortedSet&lt;&gt;。任何人都可以建议获得输入值的 floor 和 ceil 结果的最佳方法吗?

SortedSet<long> set = new SortedSet<long>();

【问题讨论】:

  • 可能是Math.FloorMath.Ceilingl 是什么?
  • @SeM,我需要在 BST 范围内运行的地板和天花板方法
  • 这在 .Net 中非常需要。如果不编写自己的数据结构,就无法实现范围广泛的算法。

标签: c# .net binary-search-tree


【解决方案1】:

如前所述,上述内容不是答案,因为这是一棵我们期望对数时间的树。 Java 的地板和天花板方法是对数的。 GetViewBetween 是对数的,Max 和 Min 也是,所以:

SortedSet&lt;long&gt; 的楼层: sortedSet.GetViewBetween(long.MinValue, num).Max

SortedSet&lt;long&gt; 的上限: sortedSet.GetViewBetween(num, long.MaxValue).Min

【讨论】:

  • 由于GetViewBetween()方法返回SortedSet,其中包含需要O(N)时间配置的Count属性,该方法没有达到对数时间复杂度。
  • 不幸的是 GetViewBetween() 是 O(N) stackoverflow.com/questions/9850975/…
  • 虽然根据某些 cmets GetViewBetween() 可能是 O(logN),但代码本身不是错误的吗? sortedSet.GetViewBetween(num, long.MaxValue).Minnum 本身。
  • @chuang 如果num 不在sortedSet 中,则不是。代码对我来说看起来是正确的。而且这里的一些cmets说dotnet core的GetViewBetweenO(logN)(同意你的观点,只是在这个问题上没有看到这样的cmets):stackoverflow.com/q/9850975/2850543
【解决方案2】:

你可以使用这样的东西。在 Linq 中有 LastOrDefault 方法:

var floor = sortedSet.LastOrDefault(i => i < num);
// num is the number whose floor is to be calculated
if (! (floor < sortedSet.ElementAt(0)))
{
  // we have a floor
}
else
 // nothing is smaller in the set
{
}

【讨论】:

  • 这不会有 Java 解决方案的对数时间复杂度,对吧?这只是一个线性搜索。
  • 同意。我认为搜索是 O(n) 的二进制。c# 中的 sortedset 与 java 中的 treeset 将成为一个很好的 SO 问题
猜你喜欢
  • 2011-03-23
  • 2012-11-28
  • 2010-11-20
  • 2019-04-15
  • 2011-01-27
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多