Hash table summary

Generally speaking, hash tables are used to quickly determine whether an element appears in a set.

For hash tables, you need to knowhash functionandhash collision The role of in the hash table.

The hash function maps the incoming key to the index of the symbol table.

Hash collision handles the situation when multiple keys are mapped to the same index. The common ways to handle collisions are the zipper method and the linear detection method.

Next are the three common hash structures:

  • array

  • set

  • map

Array as hash table

Arrays are simple hash tables, but the size of the array is limited!

Some students may think that if they use arrays for anything, they can just use map. It is indeed possible to use map for the above two questions, but the space consumption of using map is larger than that of array, because map needs to maintain a red-black tree or symbol table, and also needs to perform hash function operations. So arrays are simpler, more direct and more effective!

set as hash table

If there is no limit on the size of the value, the array cannot be used as a hash table. Mainly because of the following two points:

  • The size of the array is limited and is limited by the system stack space (not the stack of data structures).

  • If the array space is large enough, but the hash values ​​are relatively few, extremely scattered, and have a very large span, using the array will cause a huge waste of space.

map as hash table

Limitations of using arrays and sets for hashing.

  • The size of the array is limited, and if there are few elements and the hash value is too large, it will cause a waste of memory space.

  • Set is a set, and the elements placed in it can only be one key. For the question of the sum of two numbers, we not only need to determine whether y exists, but also record the subscript position of y, because we need to return the subscripts of x and y. So set cannot be used either.

  • Map is a structure of <key, value>. In this question, you can use key to save the value, and use value to save the subscript where the value is located. So using map is most appropriate.

Summarize
  • Although map is omnipotent, you still need to know when to use arrays and when to use sets.

Guess you like

Origin blog.csdn.net/weixin_48144018/article/details/134902772