在 SortedDictionary 中查找项目索引的最有效方法
我正在使用排序字典来维护项目列表,我经常需要监视其中前 x 个项目的状态。每次更新项目时,我都希望有一种快速的方法来确定我所指的项目正在使用什么索引。我知道我可以枚举整个列表并计算出我的位置,但我正在寻找 O(log n) 时间或更好的东西,毕竟排序的字典位于 RedBlack 树上。每个节点应该能够跟踪其子节点,并且这应该是一个快速计算。
I am using a sorted dictionary to maintain a list of items, of which I regularly need to monitor the state of the top x items. Every time I update an item, I'd like a quick way of figuring out what index the item I'm referring to is using. I understand I can enumerate the entire list and count out my position, but I am looking for something with O(log n) time or better, after all the sorted dictionary is on a RedBlack tree. Each node should be able to keep track of its children, and this should be a quick calculation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以构建树结构来通过索引访问项目或在 lgN 时间内报告现有项目的索引,插入和删除只需要很少的额外时间。实现此目的的一种方法是跟踪每个节点的左右分支中有多少项(在插入或删除时,在更改子节点的计数时更改父节点的节点计数)。但是,如果基于树的结构不提供这样的设施,我知道没有简单的方法来改造它。
A tree structure could be constructed to access items by index or report the index of an existing item in lgN time, requiring very slight extra time for inserts and deletes. One way to do this would be to keep track of how many items are in the left and right branches of each node (on an insert or delete, change the node count of parent nodes when changing the count of the children). If a tree-based structure does not offer such a facility, though, I know of no easy way to retrofit it.
您只需将
SortedDictionary
更改为SortedList
,然后使用IndexOfKey(key)
:IndexOfKey
内部使用Array.BinarySearch()
,因此它将是 O(log n),这比 O( n)(如果您通过迭代从前到后搜索,就会出现这种情况)。You can simply change your
SortedDictionary<TKey, TValue>
into aSortedList<TKey, TValue>
and then useIndexOfKey(key)
:IndexOfKey
internally usesArray.BinarySearch<TKey>()
, so it will be O(log n), which is faster than O(n) (which it would be if you searched from front to back by iterating through it).