Is there a Lower Bound function on a SortedList<K ,V>
? The function should return the first element equal to or greater than the specified key. Is there some other class that supports this?
Guys - please read the question once again. I do not need a function that returns the key if it is present. I'm interested in scenario when there is no exact key matching.
I'm interested in O(log n) time. It means that I do not have a problem with foreach loop, but rather would like to have an efficient way of doing this.
I have done some tests on this.
Linq statements are not optimized by neither the compiler nor runtime machine, so they walk through all collection elements and are slow O(n). Based on Mehrdad Afshari answer, here is a Binary Search that works in O(log n) on the Keys collection:
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;
}
6条答案
按热度按时间ars1skjm1#
Binary search the
SortedList.Keys
collection.Here we go. This is O(log n):
qlckcl4x2#
我会选择LINQ(假设您使用的是C#3),但是使用带 predicate 的FirstOrDefault重载:
(许多其他Enumerable方法也可以使用 predicate ,这是一个很好的快捷方式)
llmtgqce3#
Not aware of one, but it's a simple LINQ statement:
first
will either be the first object that passes the comparison ordefault(T)
(which is normallynull
).Edit
DaveW's version:
does the same job but could potentially be faster, you'd have to test it though.
flvlnr444#
或者你可以写自己的扩展方法来做这件事。注意,所有这些函数并不保证都是一个序列。
emeijp435#
zujrkrfu6#
根据SortedList的实现,希望这会更快。