数组通过整数下标 O(1) 访问,但现实中的键往往是姓名、字符串或其他离散值。哈希表通过哈希函数把键映射到桶下标,在平均情况下实现接近 O(1) 的插入、查找和删除。
哈希函数
哈希函数把任意长度的键转换为整数哈希值:
#include <stddef.h>
#include <stdint.h>
uint64_t hash_string(const char *text) {
uint64_t hash = UINT64_C(14695981039346656037);
while (*text != '\0') {
hash ^= (unsigned char)*text++;
hash *= UINT64_C(1099511628211);
}
return hash;
}
2026/7/12大约 4 分钟