一个SortedList.IndexOfKey(密钥),返回项目,其中item.key&GT的指数; =键 [英] A SortedList.IndexOfKey(key) that returns the index of the item where item.key >= key

查看:370
本文介绍了一个SortedList.IndexOfKey(密钥),返回项目,其中item.key&GT的指数; =键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

排序列表< TKEY的,TValue> .IndexOfKey(键)的返回-1,如果的不在列表

这是否意味着我必须实现二进制搜索自己,如果我想找到关键的指标是大于或等于的的名单?或者是有什么了,我忽略了箱子里吗?

我想当然的结果为O(log(n))的,所以请没有LINQ迭代和过滤器的魔力。

(一般情况下,我想有类似Java的NavigableMap的功能,如高效的迭代有序映射/字典即功能,但现在,回答了上面的问题就足够了,我可以扩展法从那里我的路不知何故)

解决方案

我怕你的运气了,没有什么内置。

如果您创建的IList℃的二分查找扩展方法; T&GT; ,那么你可以使用它对抗的 财产。这是一个有点恼人,虽然不是太困难。<​​/ P>

(框架使用内置的二进制搜索方法的公约 - 阵列 名单,其中,T&GT; - 是要返回时,未找到该元素的下一个元素的索引的按位补)

  INT指数= yourSortedList.Keys.YourBinarySearchExtensionMethod(密钥);
如果(索引&gt; = 0)
{
    //关键发现
}
其他
{
    //没有找到钥匙
}
 

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)

解决方案

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 the Keys property. This is a bit annoying, though not too difficult.

(The convention used by the framework's built-in binary search methods -- Array and List<T> -- is to return the bitwise complement of the index of the next element when the element isn't found.)

int index = yourSortedList.Keys.YourBinarySearchExtensionMethod(key);
if (index >= 0)
{
    // key found
}
else
{
    // key not found
}

这篇关于一个SortedList.IndexOfKey(密钥),返回项目,其中item.key&GT的指数; =键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆