简体   繁体   English

Java 的 TreeMap 中的关键更新

[英]Key update in Java’s TreeMap

Is there any chance to update a key of the least key entry (firstEntry()) in the TreeMap in one pass?是否有机会一次性更新 TreeMap 中最小键条目(firstEntry())的键? So, for example, if I pollFirstEntry(), it takes O(log n) time to retrieve and remove an entry.因此,例如,如果我 pollFirstEntry(),则需要 O(log n) 时间来检索和删除条目。 Afterwards, I create a new entry with desired key and put it back into TreeMap, it also takes O(log n) time.之后,我使用所需的键创建一个新条目并将其放回 TreeMap,它也需要 O(log n) 时间。 Consequently, I spend O(2 log n) time, in the case where it is logically could be just O(1+log n) = (log n) time.因此,我花费 O(2 log n) 时间,在逻辑上可能只是 O(1+log n) = (log n) 时间的情况下。

I would be very happy to avoid removing the entry, but update it while it captured by firstEntry() method.我很乐意避免删除该条目,而是在它被 firstEntry() 方法捕获时更新它。 If it is not possible with TreeMap, could anybody suggest an alternative PriorityQueue like data structure, where possible to update keys of the least entry.如果 TreeMap 不可能,有人可以建议替代 PriorityQueue 之类的数据结构,在可能的情况下更新最少条目的键。

O(2 log N) is rightly considered O(log N) . O(2 log N)被正确地视为O(log N) But no, cannot be done as in the entry in the map changes to another position (in the tree).但是不,不能在地图中的条目更改为另一个位置(在树中)时完成。 The almost only data structure where this does not hold is a list of key-value pairs, and that is a terrible O(N) or as you might like O(N/2) .几乎唯一不存在的数据结构是键值对列表,这是一个可怕的O(N)或者你可能喜欢O(N/2)

If the key can be used as index in a huge array, then O(1) would hold, still 2 operations.如果键可以用作巨大数组中的索引,那么O(1)将保持不变,仍然是 2 个操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM