上是否有下界函数SortedList<K ,V>
?该函数应返回等于或大于指定键的第一个元素。有没有其他类支持这个?
伙计们 - 请再读一遍这个问题。我不需要返回密钥(如果存在)的函数。我对没有精确键匹配的场景感兴趣。
我对 O(log n) time 感兴趣。这意味着我对 foreach 循环没有问题,而是希望有一种有效的方法来做到这一点。
我对此做了一些测试。
编译器和运行时机器都没有优化 Linq 语句,因此它们遍历所有集合元素并且速度慢 O(n)。基于 Mehrdad Afshari 的回答,这里是在 Keys 集合上以 O(log n) 工作的二进制搜索:
public static int FindFirstIndexGreaterThanOrEqualTo<T>(
this IList<T> sortedCollection, T key
) where T : IComparable<T> {
int begin = 0;
int end = sortedCollection.Count;
while (end > begin) {
int index = (begin + end) / 2;
T el = sortedCollection[index];
if (el.CompareTo(key) >= 0)
end = index;
else
begin = index + 1;
}
return end;
}