Time complexity of TreeMap operations- subMap, headMap, tailMap

前端 未结 2 532
抹茶落季
抹茶落季 2021-01-02 03:56

Does anyone know the time complexity of the operations of TreeMap like - subMap, headMap. tailMap.

The time complexity of operations like get, put is O(logn). But th

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 04:13

    I was able to browse the source of TreeMap to get the detailed implementation.

    If you go in detail with the source code as to how they are actually getting the subMap its something like this...

    If you see the size method of NavigableSubMap

      public int size() {
            return (fromStart && toEnd) ? m.size() : entrySet().size();
        }
    

    The entrySet() implementation in multiple calls final calls up getCeilingEntry() function

    final Entry getCeilingEntry(K key) {
        Entry p = root;
        while (p != null) {
            int cmp = compare(key, p.key);
            if (cmp < 0) {
                if (p.left != null)
                    p = p.left;
                else
                    return p;
            } else if (cmp > 0) {
                if (p.right != null) {
                    p = p.right;
                } else {
                    Entry parent = p.parent;
                    Entry ch = p;
                    while (parent != null && ch == parent.right) {
                        ch = parent;
                        parent = parent.parent;
                    }
                    return parent;
                }
            } else
                return p;
        }
        return null;
    }
    

    SO i guess to get the actual map from the created submap; the time complexity is more than O(1).

提交回复
热议问题