假设我有一个强类型的int类型SortedSet。 我想找到集合中小于x的最大数字。
也许这不是正确的数据结构,但我的直觉认为我有一个已排序的集合。 我应该能够通过.NET框架来进行此类搜索,这是有意义的,对吗?
SortedSet
不提供直接的索引访问,因此您必须依靠枚举(线性搜索-O(n))。一种更好的方法是使用SortedSet.GetViewBetween和Last
,但是似乎无法在枚举全部视图元素的情况下获得最后一个元素。List
)将允许您进行O(lg n)性能的二分搜索-因此,如果您需要频繁搜索,则使用ToList
进行复制可能会在使用List.BinarySearch(它为您提供要查找的下一个元素的位置)时提供更好的整体性能。// starting sample for BinarySearch approach
// not handling case where item not in the list (x = 1).
// List have to be sorted which is the case starting from sorted set: sortedSet.ToList()
var list = new List<int>{ 1,3, 5, 7, 8,9};
var index = list.BinarySearch(8);
Console.WriteLine(index < 0 ? list[~index - 1] : list[index-1]);
LastOrDefault
扩展方法:var lastBefore = set.LastOrDefault(num => num < x); // x is your search number
if (lastBefore < set.ElementAt(0))
{
// Nothing in the set is smaller
}
else
{
// lastBefore is the last number smaller then search number
}
.ToList()
... - Zohar Peled