Complexity of Treemap insertion vs HashMap insertion

前端 未结 4 1277
北海茫月
北海茫月 2021-02-05 10:08

I am confused with the time complexity of these two algorithms.

//time complexity O(nlog(n))
public void usingTreeMap(){
    Map map = ne         


        
4条回答
  •  渐次进展
    2021-02-05 10:29

    Insertion time complexity is typically defined on a per instance basis.

    Average case:

    • HashMap O(1)
    • TreeMap O(logn) -- since the underlying structure is a red-black tree

    Worst case:

    • Hashmap O(n) -- in the case of a hashing collision
    • TreeMap O(logn)

    In your code above since you are inserting multiple items, we need to distinguish how many elements are in the maps (n) vs. how many elements are being added to the maps (m). If the maps are initially empty, then your runtime above is correct. If they already have some elements, then the runtimes would be:

                                    Avg      Worst
    Insert m elements into HashMap: O(m)     O(mn)
    Inset m elements into TreeMap:  O(mlogn) O(mlogn)
    

提交回复
热议问题