This commit is contained in:
krahets
2023-06-25 21:11:35 +08:00
parent 5bc8df6d5d
commit e4e6cd6bae
19 changed files with 836 additions and 105 deletions

View File

@@ -77,7 +77,6 @@ index = hash(key) % capacity
int hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
System.out.println((int)c);
hash ^= (int) c;
}
return hash & MODULUS;
@@ -178,13 +177,53 @@ index = hash(key) % capacity
=== "Go"
```go title="simple_hash.go"
[class]{}-[func]{addHash}
/* 加法哈希 */
func addHash(key string) int {
var hash int64
var modulus int64
[class]{}-[func]{mulHash}
modulus = 1000000007
for _, b := range []byte(key) {
hash = (hash + int64(b)) % modulus
}
return int(hash)
}
[class]{}-[func]{xorHash}
/* 乘法哈希 */
func mulHash(key string) int {
var hash int64
var modulus int64
[class]{}-[func]{rotHash}
modulus = 1000000007
for _, b := range []byte(key) {
hash = (31*hash + int64(b)) % modulus
}
return int(hash)
}
/* 异或哈希 */
func xorHash(key string) int {
hash := 0
modulus := 1000000007
for _, b := range []byte(key) {
fmt.Println(int(b))
hash ^= int(b)
hash = (31*hash + int(b)) % modulus
}
return hash & modulus
}
/* 旋转哈希 */
func rotHash(key string) int {
var hash int64
var modulus int64
modulus = 1000000007
for _, b := range []byte(key) {
hash = ((hash << 4) ^ (hash >> 28) ^ int64(b)) % modulus
}
return int(hash)
}
```
=== "JavaScript"
@@ -452,7 +491,29 @@ $$
=== "Dart"
```dart title="built_in_hash.dart"
int num = 3;
int hashNum = num.hashCode;
// 整数 3 的哈希值为 34803
bool bol = true;
int hashBol = bol.hashCode;
// 布尔值 true 的哈希值为 1231
double dec = 3.14159;
int hashDec = dec.hashCode;
// 小数 3.14159 的哈希值为 2570631074981783
String str = "Hello 算法";
int hashStr = str.hashCode;
// 字符串 Hello 算法 的哈希值为 468167534
List arr = [12836, "小哈"];
int hashArr = arr.hashCode;
// 数组 [12836, 小哈] 的哈希值为 976512528
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode;
// 节点对象 Instance of 'ListNode' 的哈希值为 1033450432
```
在大多数编程语言中,**只有不可变对象才可作为哈希表的 `key`** 。假如我们将列表(动态数组)作为 `key` ,当列表的内容发生变化时,它的哈希值也随之改变,我们就无法在哈希表中查询到原先的 `value` 了。

View File

@@ -372,7 +372,128 @@ comments: true
```go title="hash_map_chaining.go"
[class]{pair}-[func]{}
[class]{hashMapChaining}-[func]{}
/* 链式地址哈希表 */
type hashMapChaining struct {
size int // 键值对数量
capacity int // 哈希表容量
loadThres float64 // 触发扩容的负载因子阈值
extendRatio int // 扩容倍数
buckets [][]pair // 桶数组
}
/* 构造方法 */
func newHashMapChaining() *hashMapChaining {
buckets := make([][]pair, 4)
for i := 0; i < 4; i++ {
buckets[i] = make([]pair, 0)
}
return &hashMapChaining{
size: 0,
capacity: 4,
loadThres: 2 / 3.0,
extendRatio: 2,
buckets: buckets,
}
}
/* 哈希函数 */
func (m *hashMapChaining) hashFunc(key int) int {
return key % m.capacity
}
/* 负载因子 */
func (m *hashMapChaining) loadFactor() float64 {
return float64(m.size / m.capacity)
}
/* 查询操作 */
func (m *hashMapChaining) get(key int) string {
idx := m.hashFunc(key)
bucket := m.buckets[idx]
// 遍历桶,若找到 key 则返回对应 val
for _, p := range bucket {
if p.key == key {
return p.val
}
}
// 若未找到 key 则返回空字符串
return ""
}
/* 添加操作 */
func (m *hashMapChaining) put(key int, val string) {
// 当负载因子超过阈值时,执行扩容
if m.loadFactor() > m.loadThres {
m.extend()
}
idx := m.hashFunc(key)
// 遍历桶,若遇到指定 key ,则更新对应 val 并返回
for _, p := range m.buckets[idx] {
if p.key == key {
p.val = val
return
}
}
// 若无该 key ,则将键值对添加至尾部
p := pair{
key: key,
val: val,
}
m.buckets[idx] = append(m.buckets[idx], p)
m.size += 1
}
/* 删除操作 */
func (m *hashMapChaining) remove(key int) {
idx := m.hashFunc(key)
// 遍历桶,从中删除键值对
for i, p := range m.buckets[idx] {
if p.key == key {
// 切片删除
m.buckets[idx] = append(m.buckets[idx][:i], m.buckets[idx][i+1:]...)
break
}
}
m.size -= 1
}
/* 扩容哈希表 */
func (m *hashMapChaining) extend() {
// 暂存原哈希表
tmpBuckets := make([][]pair, len(m.buckets))
for i := 0; i < len(m.buckets); i++ {
tmpBuckets[i] = make([]pair, len(m.buckets[i]))
copy(tmpBuckets[i], m.buckets[i])
}
// 初始化扩容后的新哈希表
m.capacity *= m.extendRatio
m.buckets = make([][]pair, m.capacity)
for i := 0; i < m.capacity; i++ {
m.buckets[i] = make([]pair, 0)
}
m.size = 0
// 将键值对从原哈希表搬运至新哈希表
for _, bucket := range tmpBuckets {
for _, p := range bucket {
m.put(p.key, p.val)
}
}
}
/* 打印哈希表 */
func (m *hashMapChaining) print() {
var builder strings.Builder
for _, bucket := range m.buckets {
builder.WriteString("[")
for _, p := range bucket {
builder.WriteString(strconv.Itoa(p.key) + " -> " + p.val + " ")
}
builder.WriteString("]")
fmt.Println(builder.String())
builder.Reset()
}
}
```
=== "JavaScript"
@@ -426,9 +547,111 @@ comments: true
=== "Dart"
```dart title="hash_map_chaining.dart"
[class]{Pair}-[func]{}
/* 键值对 */
class Pair {
int key;
String val;
Pair(this.key, this.val);
}
[class]{HashMapChaining}-[func]{}
/* 链式地址哈希表 */
class HashMapChaining {
late int size; // 键值对数量
late int capacity; // 哈希表容量
late double loadThres; // 触发扩容的负载因子阈值
late int extendRatio; // 扩容倍数
late List<List<Pair>> buckets; // 桶数组
/* 构造方法 */
HashMapChaining() {
size = 0;
capacity = 4;
loadThres = 2 / 3.0;
extendRatio = 2;
buckets = List.generate(capacity, (_) => []);
}
/* 哈希函数 */
int hashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
double loadFactor() {
return size / capacity;
}
/* 查询操作 */
String? get(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets[index];
// 遍历桶,若找到 key 则返回对应 val
for (Pair pair in bucket) {
if (pair.key == key) {
return pair.val;
}
}
// 若未找到 key 则返回 null
return null;
}
/* 添加操作 */
void put(int key, String val) {
// 当负载因子超过阈值时,执行扩容
if (loadFactor() > loadThres) {
extend();
}
int index = hashFunc(key);
List<Pair> bucket = buckets[index];
// 遍历桶,若遇到指定 key ,则更新对应 val 并返回
for (Pair pair in bucket) {
if (pair.key == key) {
pair.val = val;
return;
}
}
// 若无该 key ,则将键值对添加至尾部
Pair pair = Pair(key, val);
bucket.add(pair);
size++;
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets[index];
// 遍历桶,从中删除键值对
bucket.removeWhere((Pair pair) => pair.key == key);
size--;
}
/* 扩容哈希表 */
void extend() {
// 暂存原哈希表
List<List<Pair>> bucketsTmp = buckets;
// 初始化扩容后的新哈希表
capacity *= extendRatio;
buckets = List.generate(capacity, (_) => []);
size = 0;
// 将键值对从原哈希表搬运至新哈希表
for (List<Pair> bucket in bucketsTmp) {
for (Pair pair in bucket) {
put(pair.key, pair.val);
}
}
}
/* 打印哈希表 */
void printHashMap() {
for (List<Pair> bucket in buckets) {
List<String> res = [];
for (Pair pair in bucket) {
res.add("${pair.key} -> ${pair.val}");
}
print(res);
}
}
}
```
!!! tip
@@ -836,7 +1059,137 @@ comments: true
```go title="hash_map_open_addressing.go"
[class]{pair}-[func]{}
[class]{hashMapOpenAddressing}-[func]{}
/* 链式地址哈希表 */
type hashMapOpenAddressing struct {
size int // 键值对数量
capacity int // 哈希表容量
loadThres float64 // 触发扩容的负载因子阈值
extendRatio int // 扩容倍数
buckets []pair // 桶数组
removed pair // 删除标记
}
/* 构造方法 */
func newHashMapOpenAddressing() *hashMapOpenAddressing {
buckets := make([]pair, 4)
return &hashMapOpenAddressing{
size: 0,
capacity: 4,
loadThres: 2 / 3.0,
extendRatio: 2,
buckets: buckets,
removed: pair{
key: -1,
val: "-1",
},
}
}
/* 哈希函数 */
func (m *hashMapOpenAddressing) hashFunc(key int) int {
return key % m.capacity
}
/* 负载因子 */
func (m *hashMapOpenAddressing) loadFactor() float64 {
return float64(m.size) / float64(m.capacity)
}
/* 查询操作 */
func (m *hashMapOpenAddressing) get(key int) string {
idx := m.hashFunc(key)
// 线性探测,从 index 开始向后遍历
for i := 0; i < m.capacity; i++ {
// 计算桶索引,越过尾部返回头部
j := (idx + 1) % m.capacity
// 若遇到空桶,说明无此 key ,则返回 null
if m.buckets[j] == (pair{}) {
return ""
}
// 若遇到指定 key ,则返回对应 val
if m.buckets[j].key == key && m.buckets[j] != m.removed {
return m.buckets[j].val
}
}
// 若未找到 key 则返回空字符串
return ""
}
/* 添加操作 */
func (m *hashMapOpenAddressing) put(key int, val string) {
// 当负载因子超过阈值时,执行扩容
if m.loadFactor() > m.loadThres {
m.extend()
}
idx := m.hashFunc(key)
// 线性探测,从 index 开始向后遍历
for i := 0; i < m.capacity; i++ {
// 计算桶索引,越过尾部返回头部
j := (idx + i) % m.capacity
// 若遇到空桶、或带有删除标记的桶,则将键值对放入该桶
if m.buckets[j] == (pair{}) || m.buckets[j] == m.removed {
m.buckets[j] = pair{
key: key,
val: val,
}
m.size += 1
return
}
// 若遇到指定 key ,则更新对应 val
if m.buckets[j].key == key {
m.buckets[j].val = val
}
}
}
/* 删除操作 */
func (m *hashMapOpenAddressing) remove(key int) {
idx := m.hashFunc(key)
// 遍历桶,从中删除键值对
// 线性探测,从 index 开始向后遍历
for i := 0; i < m.capacity; i++ {
// 计算桶索引,越过尾部返回头部
j := (idx + 1) % m.capacity
// 若遇到空桶,说明无此 key ,则直接返回
if m.buckets[j] == (pair{}) {
return
}
// 若遇到指定 key ,则标记删除并返回
if m.buckets[j].key == key {
m.buckets[j] = m.removed
m.size -= 1
}
}
}
/* 扩容哈希表 */
func (m *hashMapOpenAddressing) extend() {
// 暂存原哈希表
tmpBuckets := make([]pair, len(m.buckets))
copy(tmpBuckets, m.buckets)
// 初始化扩容后的新哈希表
m.capacity *= m.extendRatio
m.buckets = make([]pair, m.capacity)
m.size = 0
// 将键值对从原哈希表搬运至新哈希表
for _, p := range tmpBuckets {
if p != (pair{}) && p != m.removed {
m.put(p.key, p.val)
}
}
}
/* 打印哈希表 */
func (m *hashMapOpenAddressing) print() {
for _, p := range m.buckets {
if p != (pair{}) {
fmt.Println(strconv.Itoa(p.key) + " -> " + p.val)
} else {
fmt.Println("nil")
}
}
}
```
=== "JavaScript"
@@ -890,9 +1243,130 @@ comments: true
=== "Dart"
```dart title="hash_map_open_addressing.dart"
[class]{Pair}-[func]{}
/* 键值对 */
class Pair {
int key;
String val;
Pair(this.key, this.val);
}
[class]{HashMapOpenAddressing}-[func]{}
/* 开放寻址哈希表 */
class HashMapOpenAddressing {
late int _size; // 键值对数量
late int _capacity; // 哈希表容量
late double _loadThres; // 触发扩容的负载因子阈值
late int _extendRatio; // 扩容倍数
late List<Pair?> _buckets; // 桶数组
late Pair _removed; // 删除标记
/* 构造方法 */
HashMapOpenAddressing() {
_size = 0;
_capacity = 4;
_loadThres = 2.0 / 3.0;
_extendRatio = 2;
_buckets = List.generate(_capacity, (index) => null);
_removed = Pair(-1, "-1");
}
/* 哈希函数 */
int hashFunc(int key) {
return key % _capacity;
}
/* 负载因子 */
double loadFactor() {
return _size / _capacity;
}
/* 查询操作 */
String? get(int key) {
int index = hashFunc(key);
// 线性探测,从 index 开始向后遍历
for (int i = 0; i < _capacity; i++) {
// 计算桶索引,越过尾部返回头部
int j = (index + i) % _capacity;
// 若遇到空桶,说明无此 key ,则返回 null
if (_buckets[j] == null) return null;
// 若遇到指定 key ,则返回对应 val
if (_buckets[j]!.key == key && _buckets[j] != _removed)
return _buckets[j]!.val;
}
return null;
}
/* 添加操作 */
void put(int key, String val) {
// 当负载因子超过阈值时,执行扩容
if (loadFactor() > _loadThres) {
extend();
}
int index = hashFunc(key);
// 线性探测,从 index 开始向后遍历
for (int i = 0; i < _capacity; i++) {
// 计算桶索引,越过尾部返回头部
int j = (index + i) % _capacity;
// 若遇到空桶、或带有删除标记的桶,则将键值对放入该桶
if (_buckets[j] == null || _buckets[j] == _removed) {
_buckets[j] = new Pair(key, val);
_size += 1;
return;
}
// 若遇到指定 key ,则更新对应 val
if (_buckets[j]!.key == key) {
_buckets[j]!.val = val;
return;
}
}
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
// 线性探测,从 index 开始向后遍历
for (int i = 0; i < _capacity; i++) {
// 计算桶索引,越过尾部返回头部
int j = (index + i) % _capacity;
// 若遇到空桶,说明无此 key ,则直接返回
if (_buckets[j] == null) {
return;
}
// 若遇到指定 key ,则标记删除并返回
if (_buckets[j]!.key == key) {
_buckets[j] = _removed;
_size -= 1;
return;
}
}
}
/* 扩容哈希表 */
void extend() {
// 暂存原哈希表
List<Pair?> bucketsTmp = _buckets;
// 初始化扩容后的新哈希表
_capacity *= _extendRatio;
_buckets = List.generate(_capacity, (index) => null);
_size = 0;
// 将键值对从原哈希表搬运至新哈希表
for (Pair? pair in bucketsTmp) {
if (pair != null && pair != _removed) {
put(pair.key, pair.val);
}
}
}
/* 打印哈希表 */
void printHashMap() {
for (Pair? pair in _buckets) {
if (pair != null) {
print("${pair.key} -> ${pair.val}");
} else {
print(null);
}
}
}
}
```
### 多次哈希

View File

@@ -1212,7 +1212,7 @@ index = hash(key) % capacity
key: usize = undefined,
val: []const u8 = undefined,
pub fn init(key: usize, val: []const u8) Pair {
pub fn init(key: usize, val: []const u8) Pair {
return Pair {
.key = key,
.val = val,
@@ -1223,25 +1223,25 @@ index = hash(key) % capacity
// 基于数组简易实现的哈希表
fn ArrayHashMap(comptime T: type) type {
return struct {
buckets: ?std.ArrayList(?T) = null,
bucket: ?std.ArrayList(?T) = null,
mem_allocator: std.mem.Allocator = undefined,
const Self = @This();
// 构造方法
// 构造函数
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
self.mem_allocator = allocator;
// 初始化数组,包含 100 个桶
self.buckets = std.ArrayList(?T).init(self.mem_allocator);
// 初始化一个长度为 100 的桶(数组)
self.bucket = std.ArrayList(?T).init(self.mem_allocator);
var i: i32 = 0;
while (i < 100) : (i += 1) {
try self.buckets.?.append(null);
try self.bucket.?.append(null);
}
}
// 析构方法
// 析构函数
pub fn deinit(self: *Self) void {
if (self.buckets != null) self.buckets.?.deinit();
if (self.bucket != null) self.bucket.?.deinit();
}
// 哈希函数
@@ -1253,7 +1253,7 @@ index = hash(key) % capacity
// 查询操作
pub fn get(self: *Self, key: usize) []const u8 {
var index = hashFunc(key);
var pair = self.buckets.?.items[index];
var pair = self.bucket.?.items[index];
return pair.?.val;
}
@@ -1261,44 +1261,44 @@ index = hash(key) % capacity
pub fn put(self: *Self, key: usize, val: []const u8) !void {
var pair = Pair.init(key, val);
var index = hashFunc(key);
self.buckets.?.items[index] = pair;
self.bucket.?.items[index] = pair;
}
// 删除操作
pub fn remove(self: *Self, key: usize) !void {
var index = hashFunc(key);
// 置为 null ,代表删除
self.buckets.?.items[index] = null;
self.bucket.?.items[index] = null;
}
// 获取所有键值对
pub fn pairSet(self: *Self) !*std.ArrayList(T) {
pub fn pairSet(self: *Self) !std.ArrayList(T) {
var entry_set = std.ArrayList(T).init(self.mem_allocator);
for (self.buckets.?.items) |item| {
for (self.bucket.?.items) |item| {
if (item == null) continue;
try entry_set.append(item.?);
}
return &entry_set;
return entry_set;
}
// 获取所有键
pub fn keySet(self: *Self) !*std.ArrayList(usize) {
pub fn keySet(self: *Self) !std.ArrayList(usize) {
var key_set = std.ArrayList(usize).init(self.mem_allocator);
for (self.buckets.?.items) |item| {
for (self.bucket.?.items) |item| {
if (item == null) continue;
try key_set.append(item.?.key);
}
return &key_set;
return key_set;
}
// 获取所有值
pub fn valueSet(self: *Self) !*std.ArrayList([]const u8) {
pub fn valueSet(self: *Self) !std.ArrayList([]const u8) {
var value_set = std.ArrayList([]const u8).init(self.mem_allocator);
for (self.buckets.?.items) |item| {
for (self.bucket.?.items) |item| {
if (item == null) continue;
try value_set.append(item.?.val);
}
return &value_set;
return value_set;
}
// 打印哈希表
@@ -1405,7 +1405,7 @@ index = hash(key) % capacity
## 6.1.3. &nbsp; 哈希冲突与扩容
本质上看,哈希函数的作用是输入空间(`key` 范围)映射到输出空间(数组索引范围),而输入空间往往远大于输出空间。因此,**理论上一定存在“多个输入对应相同输出”的情况**。
本质上看,哈希函数的作用是输入空间(`key` 范围)映射到输出空间(数组索引范围),而输入空间往往远大于输出空间。因此,**理论上一定存在“多个输入对应相同输出”的情况**。
对于上述示例中的哈希函数,当输入的 `key` 后两位相同时,哈希函数的输出结果也相同。例如,查询学号为 12836 和 20336 的两个学生时,我们得到:

View File

@@ -17,3 +17,33 @@ comments: true
- 哈希算法通常采用大质数作为模数,以最大化地保证哈希值的均匀分布,减少哈希冲突。
- 常见的哈希算法包括 MD5, SHA-1, SHA-2, SHA3 等。MD5 常用语校验文件完整性SHA-2 常用于安全应用与协议。
- 编程语言通常会为数据类型提供内置哈希算法,用于计算哈希表中的桶索引。通常情况下,只有不可变对象是可哈希的。
## 6.4.1. &nbsp; Q & A
!!! question "哈希表的时间复杂度为什么不是 $O(n)$ "
当哈希冲突比较严重时,哈希表的时间复杂度会退化至 $O(n)$ 。当哈希函数设计的比较好、容量设置比较合理、冲突比较平均时,时间复杂度是 $O(1)$ 。我们使用编程语言内置的哈希表时,通常认为时间复杂度是 $O(1)$ 。
!!! question "为什么不使用哈希函数 $f(x) = x$ 呢?这样就不会有冲突了"
在 $f(x) = x$ 哈希函数下,每个元素对应唯一的桶索引,这与数组等价。然而,输入空间通常远大于输出空间(数组长度),因此哈希函数的最后一步往往是对数组长度取模。换句话说,哈希表的目标是将一个较大的状态空间映射到一个较小的空间,并提供 $O(1)$ 的查询效率。
!!! question "哈希表底层实现是数组、链表、二叉树,但为什么效率可以比他们更高呢?"
首先,哈希表的时间效率变高,但空间效率变低了。哈希表有相当一部分的内存是未使用的,
其次,只是在特定使用场景下时间效率变高了。如果一个功能能够在相同的时间复杂度下使用数组或链表实现,那么通常比哈希表更快。这是因为哈希函数计算需要开销,时间复杂度的常数项更大。
最后,哈希表的时间复杂度可能发生劣化。例如在链式地址中,我们采取在链表或红黑树中执行查找操作,仍然有退化至 $O(n)$ 时间的风险。
!!! question "多次哈希有不能直接删除元素的缺陷吗?对于标记已删除的空间,这个空间还能再次使用吗?"
多次哈希是开放寻址的一种,开放寻址法都有不能直接删除元素的缺陷,需要通过标记删除。被标记为已删除的空间是可以再次被使用的。当将新元素插入哈希表,并且通过哈希函数找到了被标记为已删除的位置时,该位置可以被新的元素使用。这样做既能保持哈希表的探测序列不变,又能保证哈希表的空间使用率。
!!! question "为什么在线性探测中,查找元素的时候会出现哈希冲突呢?"
查找的时候通过哈希函数找到对应的桶和键值对,发现 `key` 不匹配,这就代表有哈希冲突。因此,线性探测法会根据预先设定的步长依次向下查找,直至找到正确的键值对或无法找到跳出为止。
!!! question "为什么哈希表扩容能够缓解哈希冲突?"
哈希函数的最后一步往往是对数组长度 $n$ 取余,让输出值落入在数组索引范围;在扩容后,数组长度 $n$ 发生变化,而 `key` 对应的索引也可能发生变化。原先落在同一个桶的多个 `key` ,在扩容后可能会被分配到多个桶中,从而实现哈希冲突的缓解。