简体   繁体   English

如何从 Java TreeMap 中的给定键进行迭代

[英]How to iterate from a given key in Java TreeMap

I have a TreeMap, and want to get a set of K smallest keys (entries) larger than a given value.我有一个 TreeMap,并希望获得一组大于给定值的 K 最小键(条目)。

I know we can use higherKey(givenValue) get the one key, but then how should I iterate from there?我知道我们可以使用higherKey(givenValue)获取唯一的密钥,但是我应该如何从那里迭代呢?

One possible way is to get a tailMap from the smallest key larger than the given value, but that's an overkill if K is small compared with the map size.一种可能的方法是从大于给定值的最小键获取tailMap ,但如果 K 与 map 大小相比较小,那就太过分了。

Is there a better way with O(logn + K) time complexity? O(logn + K) 时间复杂度有更好的方法吗?

The error here is thinking that tailMap makes a new map. It doesn't.这里的错误是认为tailMap生成了一个新的 map。它没有。 It gives you a lightweight object that basically just contains a field pointing back to the original map, and the pivot point, that's all it has.它为您提供了一个轻量级的 object,它基本上只包含一个指向原始 map 的字段,以及 pivot 点,仅此而已。 Any changes you make to a tailMap map will therefore also affect the underlying map, and any changes made to the underlying map will also affect your tailMap.因此,您对tailMap map 所做的任何更改也会影响底层 map,而对底层 map 所做的任何更改也会影响您的 tailMap。

for (KeyType key : treeMap.tailMap(pivot).keySet()) {
}

The above IS O(logn) complexity for the tailMap operation, and give that you loop, that adds K to the lot, for a grand total of O(logn+K) time complexity, and O(1) space complexity, where N is the size of the map and K is the number of keys that end up being on the selected side of the pivot point (so, worst case, O(nlogn) ).以上是 tailMap操作的O(logn)复杂tailMap ,并给你循环,将K添加到地段,总计O(logn+K)时间复杂度和 O(1) 空间复杂度,其中 N是 map 的大小,K 是最终位于 pivot 点的选定侧的键的数量(因此,最坏的情况是O(nlogn) )。

If you want an actual copied-over map, you'd do something like:如果你想要一个实际复制过来的 map,你会这样做:

TreeMap<KeyType> tm = new TreeMap<KeyType>(original.tailMap(pivot));

Note that this also copies over the used comparator, in case you specified a custom one.请注意,如果您指定了自定义比较器,这也会复制使用过的比较器。 That one really is O(logn + K) in time complexity (and O(K) in space complexity).那一个在时间复杂度上确实是O(logn + K) (在空间复杂度上是O(K) )。 Of course, if you loop through this code, it's.. still O(logn + K) (because 2K just boils down to K when talking about big-O notation).当然,如果你循环遍历这段代码,它仍然是O(logn + K) (因为在谈论大 O 表示法时 2K 只是归结为 K)。

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

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