[英]Java TreeMap get Kth smallest key
I am using a TreeMap and want to get the Kth smallest key. 我正在使用TreeMap,并希望获取第K个最小键。 I wrote the following implementation: 我编写了以下实现:
public static Long kthKey(TreeMap<Long, MyObject> treeMap, int kth) {
Long currentKey = treeMap.firstKey();
for (int i = 1; i < kth; i++) {
currentKey = treeMap.higherKey(currentKey);
}
return currentKey;
}
This is pretty efficient in terms of memory, but maybe not in terms of running time. 就内存而言,这是非常有效的,但就运行时间而言可能并非如此。
Is there a more efficient way to do this? 有没有更有效的方法可以做到这一点?
If you are allowed to use an iterator, you can do this. 如果允许使用迭代器,则可以执行此操作。
public <T> static Long kthKey(Map<T, ?> map, int kth) {
for(T key: map.keySet())
if(kth-- < 1) return key;
return null;
}
The cost of one iterator is not so high, and if you need to avoid this I would suggest looking at how this method is called and optimising that eg say you have 一个迭代器的成本不是很高,如果您需要避免这种情况,我建议您看一下如何调用此方法并对其进行优化,例如说您拥有
for (int k = 0; k < mapsize(); k++) {
Long l = kthKey(map, k);
You can eliminate the need to call this method at all. 您完全不需要调用此方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.