A hash table is an efficient data structure that maps keys to indexes in an array through a hash function to achieve fast data storage and retrieval. In actual combat, it can be used to efficiently count the number of occurrences of a word: ① Use a hash table to map each word to a counter; ② When a word is encountered, check whether the key exists in the hash table; ③ If not , add it and set the count to 1; ④ If there is, add 1 to the count.
PHP Data Structure: The Secret of Hash Table
Introduction to Hash Table
A hash table is an efficient data structure used to store and quickly retrieve data. It maps keys to values and uses a hash function to convert the keys into indices that can be used in the array.
Hash function
The hash function is the magic formula that converts keys into indices. The ideal hash function is:
Practical case: word counter
Suppose we have a text file and we need to count the number of occurrences of each word. A naive solution would be to use an array to store the words and their counts, but as the number of words increases, finding and updating the counts becomes less efficient.
Using a hash table, we can map each word to a counter and use the word directly as the key. When we encounter a word, we can quickly check if the key exists in the hash table, and if not, we add it and set its count to 1. If so, we add 1 to the count.
class WordCounter { private $words = []; public function countWords($text) { $words = explode(' ', $text); foreach ($words as $word) { if (isset($this->words[$word])) { $this->words[$word]++; } else { $this->words[$word] = 1; } } } public function getWordCount($word) { return $this->words[$word] ?? 0; } }
In this example, the $words
array acts as a hash table, the keys are words and the values are counts. The function countWords()
efficiently calculates the count of each word, while the function getWordCount()
allows us to quickly retrieve the count of a specific word.
The above is the detailed content of PHP data structure: the secret of hash table, a powerful tool for mining fast queries. For more information, please follow other related articles on the PHP Chinese website!