在 SortedDictionary 中查找项目索引的最有效方法

发布于 2024-09-18 11:41:06 字数 178 浏览 2 评论 0原文

我正在使用排序字典来维护项目列表,我经常需要监视其中前 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

离线来电— 2024-09-25 11:41:07

可以构建树结构来通过索引访问项目或在 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.

奢欲 2024-09-25 11:41:06

您只需将 SortedDictionary 更改为 SortedList,然后使用 IndexOfKey(key)

var s = new SortedList<string, string>
    { { "a", "Ay" }, { "b", "Bee" }, { "c", "Cee" } };

// Outputs 1
Console.WriteLine(s.IndexOfKey("b"));

IndexOfKey 内部使用 Array.BinarySearch(),因此它将是 O(log n),这比 O( n)(如果您通过迭代从前到后搜索,就会出现这种情况)。

You can simply change your SortedDictionary<TKey, TValue> into a SortedList<TKey, TValue> and then use IndexOfKey(key):

var s = new SortedList<string, string>
    { { "a", "Ay" }, { "b", "Bee" }, { "c", "Cee" } };

// Outputs 1
Console.WriteLine(s.IndexOfKey("b"));

IndexOfKey internally uses Array.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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文