Why is a hash table lookup only O(1) time when searching for a key is O(n)?

前端 未结 4 1860
予麋鹿
予麋鹿 2021-01-12 09:16

Technically speaking, based on posts I\'ve read here, Hash table is indeed O(n) time lookup in the worst case. But I don\'t get how the internal mechanics guarantee it to be

4条回答
  •  有刺的猬
    2021-01-12 09:17

    i think the word "hash" is scaring people. Behind the scene, hash tables are data structures that stores the key/value pairs in an array.

    The only difference here is, we do not care about the position of the key value pair. There is no INDEX here. Look up for an array item O(1). it is independent of size of the array and independent of position. you just enter index number, and item is retrieved.

    so how much time did look up need to complete. it is O(1).

    In hash tables, when you store key/value pair, key value gets hashed and stored in the corresponding memory slot.

    {name:"bob"} //name will be hashed
    
    hash(name) = ab1234wq //this is the memory address
    [["name","bob"]] // will be store at memory adress ab1234wq
    

    when you look up for "name", it will get hashed and as the main feature of hashing functions, it will return same the result "ab1234wq". So the programming engine will look at this address, will see the array and will return the value. As you can see, this operation is same as array look up.

提交回复
热议问题