Worse case time complexity put/get HashMap

前端 未结 5 1983
后悔当初
后悔当初 2021-02-10 22:41

What is the worst case time complexity of an Hashmap when the hashcode of it\'s keys are always equal.

In my understanding: As every key has the same hashcode it will al

5条回答
  •  渐次进展
    2021-02-10 23:48

    in open hashing, you will have a linked list to store objects which have the same hashcode. so: for example, you have a hashed table with size 4. 1) assume you want to store an object with hashcode = 0. the object then will be mapped into index (0 mod 4 = ) 0. 2) then you again want to put another object with hashcode = 8. this object will be mapped into index (8 mod 4 = ) 0, as we remember that the index 0 has already filled with our first object, so we have to put the second next to the first.

    [0]=>linkedList{object1, object2}
    [1]=>null
    [2]=>null
    [3]=>null
    

    3) what are the steps for searching? 1st, you have to hash the key object and assume that it hashcode is 8, so you will be redirected to index (8 mod 4 = ) 0, then because there is more than one object stored in the same index, we have to search one-by-one all stored objects in the list until you find the matched one or until the end of the list. as the example has 2 objects which stored in the same hashtable index 0, and the searched object lies right in the end of the linkedlist, so you need to walk through all the stored objects. that's why it is O(n) as the worst case. worst case occured when all the stored object are in the same index in the hashtable. so they will be stored in a linkedlist in which we (may) need to walk through all of them to find our searched object.

    hope this help,.

提交回复
热议问题