NavigableMap的floorEntry()方法的时间复杂度是多少?

时间:2017-08-24 08:17:13

标签: java sortedmap

如果我已经形成了NavigableMapfloorEntry()操作执行所需的时间是多少?会是O(1)还是O(logn)

例如:

如果我的NavigableMap有n个区间,并且我使用map.floorEntry(k)来表示某个随机k,那么执行该操作的时间复杂度是多少?

1 个答案:

答案 0 :(得分:1)

NavigableMap是一个接口,所以我无法回答该接口的任何实现。但是,对于TreeMap实施,floorEntry()需要log(n)时间。

TreeMap的Javadoc仅表明

  

此实现为containsKey,get,put和remove操作提供了有保证的log(n)时间成本

floorEntry()的实施与复杂性get()的实施类似。

两者都调用执行大部分逻辑的辅助方法(get()调用getEntry()floorEntry()调用getFloorEntry()),并且两个辅助方法都有一个while循环在每次迭代中前进到左或右子,直到它找到它正在寻找或到达叶子。因此,所需的时间是树的深度 - O(log(n))

以下是getEntry()floorEntry()的实施方式:

/**
 * Returns this map's entry for the given key, or {@code null} if the map
 * does not contain an entry for the key.
 *
 * @return this map's entry for the given key, or {@code null} if the map
 *         does not contain an entry for the key
 * @throws ClassCastException if the specified key cannot be compared
 *         with the keys currently in the map
 * @throws NullPointerException if the specified key is null
 *         and this map uses natural ordering, or its comparator
 *         does not permit null keys
 */
final Entry<K,V> getEntry(Object key) {
    // Offload comparator-based version for sake of performance
    if (comparator != null)
        return getEntryUsingComparator(key);
    if (key == null)
        throw new NullPointerException();
    @SuppressWarnings("unchecked")
        Comparable<? super K> k = (Comparable<? super K>) key;
    Entry<K,V> p = root;
    while (p != null) {
        int cmp = k.compareTo(p.key);
        if (cmp < 0)
            p = p.left;
        else if (cmp > 0)
            p = p.right;
        else
            return p;
    }
    return null;
}

/**
 * Gets the entry corresponding to the specified key; if no such entry
 * exists, returns the entry for the greatest key less than the specified
 * key; if no such entry exists, returns {@code null}.
 */
final Entry<K,V> getFloorEntry(K key) {
    Entry<K,V> p = root;
    while (p != null) {
        int cmp = compare(key, p.key);
        if (cmp > 0) {
            if (p.right != null)
                p = p.right;
            else
                return p;
        } else if (cmp < 0) {
            if (p.left != null) {
                p = p.left;
            } else {
                Entry<K,V> parent = p.parent;
                Entry<K,V> ch = p;
                while (parent != null && ch == parent.left) {
                    ch = parent;
                    parent = parent.parent;
                }
                return parent;
            }
        } else
            return p;

    }
    return null;
}