Find The Closest Answer in HashMap

前端 未结 6 1115
谎友^
谎友^ 2020-12-16 13:07

I want to search for a key in a hashmap and find the nearest one to that key!

    HashMap map = new HashMap();
         


        
6条回答
  •  攒了一身酷
    2020-12-16 13:38

    Solution :

    1. If you are inserting values into the hashMap in a sorted order you could use a LinkedHashMap so that the insertion order can be maintained.

    2. Now we can perform a binary search over the keys instead of iterating over all keys (like in some of the other answers).

    3. If iteration over all keys took n comparisons, binary search would take log(n)with base 2 comparisons.

    The point to note here would be that this works only if the map is sorted.

    Comparison of diff maps :

    • A hash map is good as a general purpose map implementation that provides rapid storage and retrieval operations. However, it falls short because of its chaotic and unorderly arrangement of entries.

      This causes it to perform poorly in scenarios where there is a lot of iteration as the entire capacity of the underlying array affects traversal other than just the number of entries.

    • A linked hash map possesses the good attributes of hash maps and adds order to the entries. It performs better where there is a lot of iteration because only the number of entries is taken into account regardless of capacity.
    • A tree map takes ordering to the next level by providing complete control over how the keys should be sorted. On the flip side, it offers worse general performance than the other two alternatives.

    We could say a linked hash map reduces the chaos in the ordering of a hash map without incurring the performance penalty of a tree map.

提交回复
热议问题