中文版
哈希表(Hash Table) 是一种高效的键值对存储数据结构。哈希表通过一个哈希函数将键映射到一个数组中的位置(即索引),从而实现快速的数据存取。哈希表的核心思想是将大量数据通过哈希函数转换为一个有限范围内的数组索引,从而实现 O ( 1 ) O(1) O(1)的平均时间复杂度。
哈希表中可能会出现不同的键被映射到相同的索引的情况,这种现象称为“哈希冲突”。常见的解决哈希冲突的方法包括:
- 链地址法(Separate Chaining):为每个数组索引维护一个链表,将所有哈希冲突的键值对存储在同一个链表中。
- 开放地址法(Open Addressing):当发生冲突时,尝试探查数组中的其他位置,直到找到一个空位。
时间复杂度:
- 查找(Search):在理想情况下(冲突少),查找的时间复杂度为 O ( 1 ) O(1) O(1)。在最坏情况下(大量冲突),查找的时间复杂度可能退化为 O ( n ) O(n) O(n)。
- 插入(Insert):插入操作的时间复杂度在平均情况下为 O ( 1 ) O(1) O(1),在最坏情况下为 O ( n ) O(n) O(n)。
- 删除(Delete):删除操作的时间复杂度在平均情况下为 O ( 1 ) O(1) O(1),在最坏情况下为 O ( n ) O(n) O(n)。
English Version
A Hash Table is an efficient data structure for storing key-value pairs. A hash table uses a hash function to map keys to positions (i.e., indexes) in an array, enabling fast data access. The core idea behind a hash table is to convert large amounts of data into an array index within a finite range using a hash function, achieving an average time complexity of O ( 1 ) O(1) O(1).
However, hash tables may encounter situations where different keys are mapped to the same index, known as a “hash collision.” Common methods to resolve hash collisions include:
- Separate Chaining: Each array index maintains a linked list, and all key-value pairs that hash to the same index are stored in the same list.
- Open Addressing: When a collision occurs, the algorithm probes other positions in the array until an empty spot is found.
Time Complexity:
- Search: In the ideal case (few collisions), the time complexity for searching is O ( 1 ) O(1) O(1). In the worst case (many collisions), the time complexity can degrade to O ( n ) O(n) O(n).
- Insert: The time complexity for insertion is O ( 1 ) O(1) O(1) on average, but it can be O ( n ) O(n) O(n) in the worst case.
- Delete: The time complexity for deletion is O ( 1 ) O(1) O(1) on average, but it can be O ( n ) O(n) O(n) in the worst case.