如果 key 不在列表中,SortedList.IndexOfKey(key) 返回 -1。
这是否意味着如果我想在列表中查找大于或等于 key 的键的索引,我必须自己实现二分搜索?或者有什么开箱即用的东西被我忽略了?
当然,我想在 O(log(n)) 内获得结果,所以请不要使用 LINQ 迭代和过滤魔法。
(一般来说,我希望拥有类似Java的NavigableMap功能,即对排序的地图/字典进行高效迭代之类的功能,但现在,上述问题的答案就足够了,我可以用我的方式“扩展方法”从那里以某种方式)
SortedList<TKey, TValue>.IndexOfKey(key) returns -1 if key is not in the list.
Does this mean I have to implement a binary search myself if I want to find the index of the key in the list that is greater or equal to key? Or is there something out of the box that I overlooked?
I want to get the result in O(log(n)) of course, so please no LINQ iterate and filter magic.
(In general, I'd like to have something like Java's NavigableMap functionality, i.e. features like efficient iteration over a sorted map/dictionary, but for now, an answer to the above question would suffice, I can "extension-method" my way from there somehow)
发布评论
评论(2)
所以,对于包括我自己在内的子孙后代,我再次需要 .net 中的
NavigableMap
。适用于SortedList
的BinarySearch
扩展方法以及适用于任何IList
的重载。注意:我想知道为什么 .net 中没有
IRandomAccess
,至少可以派生出IList
和数组。SortedList
实际上可以派生自IRandomAccess
,以及IRandomAccess
和IRandomAccess>
。So here it is, for posterity, including myself, as I'm yet again in need of a
NavigableMap
in .net.BinarySearch
extension methods that work forSortedList<TKey, TValue>
and overloads that work for anyIList<T>
.N.B. I wonder why there is no
IRandomAccess<T>
in .net, which at leastIList<T>
and arrays would derive from.SortedList<TKey, TValue>
could actually derive fromIRandomAccess<TKey>
, as well asIRandomAccess<TValue>
andIRandomAccess<KeyValuePair<TKey, TValue>>
.恐怕你不走运,没有任何内置的东西。
如果您为
IList
创建二分搜索扩展方法,则可以将其用于Keys
属性。这有点烦人,但不太困难。(框架的内置二进制搜索方法使用的约定 -
Array
和List
-- 是在没有找到该元素时返回下一个元素索引的按位补码。)I'm afraid you're out of luck, there's nothing built-in.
If you create a binary search extension method for
IList<T>
then you could use it against theKeys
property. This is a bit annoying, though not too difficult.(The convention used by the framework's built-in binary search methods --
Array
andList<T>
-- is to return the bitwise complement of the index of the next element when the element isn't found.)