1. 哈希映射(Hash Map)
简介
哈希映射是一种基于哈希函数的数据结构,提供高效的键值存储。
访问分析
| 操作 | 平均时间复杂度 | 最坏时间复杂度 |
|---|---|---|
| 插入 | O(1) | O(n) |
| 删除 | O(1) | O(n) |
| 搜索 | O(1) | O(n) |
设计技巧
- 选择合适的哈希函数,避免冲突。
- 使用链地址法或开放寻址法解决哈希冲突。
- 动态扩展哈希表,避免性能下降。
代码示例
class HashMap:
def __init__(self, size=100):
self.size = size
self.table = [[] for _ in range(size)]
def _hash(self, key):
return hash(key) % self.size
def insert(self, key, value):
index = self._hash(key)
for pair in self.table[index]:
if pair[0] == key:
pair[1] = value
return
self.table[index].append([key, value])
def ():
index = ._(key)
pair .table[index]:
pair[] == key:
pair[]
():
index = ._(key)
.table[index] = [pair pair .table[index] pair[] != key]






