This commit is contained in:
krahets
2025-03-14 17:51:03 +08:00
parent c458348df2
commit e81bc45c43
31 changed files with 392 additions and 394 deletions

View File

@@ -354,7 +354,7 @@ index = hash(key) % capacity
for (const c of key) {
hash ^= c.charCodeAt(0);
}
return hash & MODULUS;
return hash % MODULUS;
}
/* 旋转哈希 */
@@ -398,7 +398,7 @@ index = hash(key) % capacity
for (const c of key) {
hash ^= c.charCodeAt(0);
}
return hash & MODULUS;
return hash % MODULUS;
}
/* 旋转哈希 */

View File

@@ -1025,10 +1025,10 @@ comments: true
```rust title="hash_map_chaining.rs"
/* 链式地址哈希表 */
struct HashMapChaining {
size: i32,
capacity: i32,
size: usize,
capacity: usize,
load_thres: f32,
extend_ratio: i32,
extend_ratio: usize,
buckets: Vec<Vec<Pair>>,
}
@@ -1046,7 +1046,7 @@ comments: true
/* 哈希函数 */
fn hash_func(&self, key: i32) -> usize {
key as usize % self.capacity as usize
key as usize % self.capacity
}
/* 负载因子 */
@@ -1057,12 +1057,11 @@ comments: true
/* 删除操作 */
fn remove(&mut self, key: i32) -> Option<String> {
let index = self.hash_func(key);
let bucket = &mut self.buckets[index];
// 遍历桶,从中删除键值对
for i in 0..bucket.len() {
if bucket[i].key == key {
let pair = bucket.remove(i);
for (i, p) in self.buckets[index].iter_mut().enumerate() {
if p.key == key {
let pair = self.buckets[index].remove(i);
self.size -= 1;
return Some(pair.val);
}
@@ -1075,7 +1074,7 @@ comments: true
/* 扩容哈希表 */
fn extend(&mut self) {
// 暂存原哈希表
let buckets_tmp = std::mem::replace(&mut self.buckets, vec![]);
let buckets_tmp = std::mem::take(&mut self.buckets);
// 初始化扩容后的新哈希表
self.capacity *= self.extend_ratio;
@@ -1109,30 +1108,27 @@ comments: true
}
let index = self.hash_func(key);
let bucket = &mut self.buckets[index];
// 遍历桶,若遇到指定 key ,则更新对应 val 并返回
for pair in bucket {
for pair in self.buckets[index].iter_mut() {
if pair.key == key {
pair.val = val;
return;
}
}
let bucket = &mut self.buckets[index];
// 若无该 key ,则将键值对添加至尾部
let pair = Pair { key, val };
bucket.push(pair);
self.buckets[index].push(pair);
self.size += 1;
}
/* 查询操作 */
fn get(&self, key: i32) -> Option<&str> {
let index = self.hash_func(key);
let bucket = &self.buckets[index];
// 遍历桶,若找到 key ,则返回对应 val
for pair in bucket {
for pair in self.buckets[index].iter() {
if pair.key == key {
return Some(&pair.val);
}