我正在写一个特定的优先级队列。它的结构需要如下所示:
Priority(<int>) Data(List<Object>)
1 a, b, g, h
3 c, d, j
4 k
10 e, f, i
我需要能够有效地查找给定优先级是否存在列表;如果没有,则创建列表并添加消息,否则将消息追加到现有列表中。
我写了一个红黑树,但这似乎有点矫枉过正,而且可能不是最快的解决方案。它还有一个缺点,就是无法轻松地按优先级抓取消息,而我需要在写入完成后才能做到这一点。
我想到了 Dictionary,但除非我弄错了,否则它没有一个简单的方法来表示“如果键 __ 存在,则给我对应的值,否则给我 null”。或者我错过了什么?
编辑
我当前的实现是有 32 个固定列表。将适用列表添加到 32 位标志中,并在 32 位标志中设置适用位。我使用 De Bruijn 算法来获取 LSB。这很有效,但增加了我想要减轻的其他复杂性。
I am writing a specific priority queue. Its structure needs to be something as follows:
Priority(<int>) Data(List<Object>)
1 a, b, g, h
3 c, d, j
4 k
10 e, f, i
I need to be able to efficiently find if a list exists for a given priority; if not, create the list and add the message, otherwise append the message to the existing list.
I have written a red-black tree, but this seems like overkill for this, and may not be the fastest solution. It also has the drawback of not being able to easily grab the messages by priority, which I need to be able to do once the writing has been completed.
I thought about Dictionary, but unless I am mistaken, it doesn't have a simple way to say "if the key __ exists, give me the value corresponding to it, otherwise give me null". Or am I missing something?
EDIT
My current implementation is to have 32 fixed lists. The applicable list is added to and the applicable bit set in a 32-bit flag. I use De Bruijn's algorithm to get the LSB. This is efficient, but is adding other complexity that I want to alleviate.
发布评论
评论(3)
也许你应该使用
Dictionary>
Maybe you should use
Dictionary<int,List<object>>
SortedDictionary 可以完成这项工作。只需使用 TryGetValue() 有条件地查找列表即可。
A SortedDictionary would fill the job. Just use TryGetValue() to conditionally find the list.
嗯,
Dictionary
作为底层容器有什么问题吗?平均而言,您获得 O(1) 访问/插入时间,而不是 rb 树的 O(log n) 时间。只需根据您的需要包装Dictionary
即可,例如:Hm, what's wrong with
Dictionary
as the underlying container? You get O(1) access/insertion time on average, instead of O(log n) with rb-trees. Just wrapDictionary
according to your needs, for example: