Add the codes of hashmap (#553)

of chaining and open addressing
This commit is contained in:
Yudong Jin
2023-06-14 02:01:06 +08:00
committed by GitHub
parent d3e597af94
commit 9563965a20
27 changed files with 1280 additions and 207 deletions
+19 -19
View File
@@ -10,24 +10,24 @@
# define HASH_MAP_DEFAULT_SIZE 100
/* 键值对 int->string */
struct Entry {
struct pair {
int key;
char *val;
};
typedef struct Entry Entry;
typedef struct pair pair;
/* 用于表示键值对、键、值的集合 */
struct MapSet {
struct mapSet {
void *set;
int len;
};
typedef struct MapSet MapSet;
typedef struct mapSet mapSet;
/* 基于数组简易实现的哈希表 */
struct ArrayHashMap {
Entry *buckets[HASH_MAP_DEFAULT_SIZE];
pair *buckets[HASH_MAP_DEFAULT_SIZE];
};
typedef struct ArrayHashMap ArrayHashMap;
@@ -47,7 +47,7 @@ int hashFunc(int key) {
/* 查询操作 */
const char *get(const ArrayHashMap *d, const int key) {
int index = hashFunc(key);
const Entry *pair = d->buckets[index];
const pair *pair = d->buckets[index];
if (pair == NULL)
return NULL;
return pair->val;
@@ -55,7 +55,7 @@ const char *get(const ArrayHashMap *d, const int key) {
/* 添加操作 */
void put(ArrayHashMap *d, const int key, const char *val) {
Entry *pair = malloc(sizeof(Entry));
pair *pair = malloc(sizeof(pair));
pair->key = key;
pair->val = malloc(strlen(val) + 1);
strcpy(pair->val, val);
@@ -73,19 +73,19 @@ void removeItem(ArrayHashMap *d, const int key) {
}
/* 获取所有键值对 */
void entrySet(ArrayHashMap *d, MapSet *set) {
Entry *entries;
void pairSet(ArrayHashMap *d, mapSet *set) {
pair *entries;
int i = 0, index = 0;
int total = 0;
/* 统计有效 entry 数量 */
/* 统计有效键值对数量 */
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
total++;
}
}
entries = malloc(sizeof(Entry) * total);
entries = malloc(sizeof(pair) * total);
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
entries[index].key = d->buckets[i]->key;
@@ -100,12 +100,12 @@ void entrySet(ArrayHashMap *d, MapSet *set) {
}
/* 获取所有键 */
void keySet(ArrayHashMap *d, MapSet *set) {
void keySet(ArrayHashMap *d, mapSet *set) {
int *keys;
int i = 0, index = 0;
int total = 0;
/* 统计有效 entry 数量 */
/* 统计有效键值对数量 */
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
total++;
@@ -125,12 +125,12 @@ void keySet(ArrayHashMap *d, MapSet *set) {
}
/* 获取所有值 */
void valueSet(ArrayHashMap *d, MapSet *set) {
void valueSet(ArrayHashMap *d, mapSet *set) {
char **vals;
int i = 0, index = 0;
int total = 0;
/* 统计有效 entry 数量 */
/* 统计有效键值对数量 */
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
total++;
@@ -152,9 +152,9 @@ void valueSet(ArrayHashMap *d, MapSet *set) {
/* 打印哈希表 */
void print(ArrayHashMap *d) {
int i;
MapSet set;
entrySet(d, &set);
Entry *entries = (Entry*) set.set;
mapSet set;
pairSet(d, &set);
pair *entries = (pair*) set.set;
for (i = 0; i < set.len; i++) {
printf("%d -> %s\n", entries[i].key, entries[i].val);
}
@@ -193,7 +193,7 @@ int main() {
printf("\n遍历键值对 Key->Value\n");
print(map);
MapSet set;
mapSet set;
keySet(map, &set);
int *keys = (int*) set.set;
+16 -16
View File
@@ -6,12 +6,12 @@
#include "../utils/common.hpp"
/* 键值对 int->String */
struct Entry {
/* 键值对 */
struct Pair {
public:
int key;
string val;
Entry(int key, string val) {
Pair(int key, string val) {
this->key = key;
this->val = val;
}
@@ -20,12 +20,12 @@ struct Entry {
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
private:
vector<Entry *> buckets;
vector<Pair *> buckets;
public:
ArrayHashMap() {
// 初始化数组,包含 100 个桶
buckets = vector<Entry *>(100);
buckets = vector<Pair *>(100);
}
~ArrayHashMap() {
@@ -45,7 +45,7 @@ class ArrayHashMap {
/* 查询操作 */
string get(int key) {
int index = hashFunc(key);
Entry *pair = buckets[index];
Pair *pair = buckets[index];
if (pair == nullptr)
return nullptr;
return pair->val;
@@ -53,7 +53,7 @@ class ArrayHashMap {
/* 添加操作 */
void put(int key, string val) {
Entry *pair = new Entry(key, val);
Pair *pair = new Pair(key, val);
int index = hashFunc(key);
buckets[index] = pair;
}
@@ -67,20 +67,20 @@ class ArrayHashMap {
}
/* 获取所有键值对 */
vector<Entry *> entrySet() {
vector<Entry *> entrySet;
for (Entry *pair : buckets) {
vector<Pair *> pairSet() {
vector<Pair *> pairSet;
for (Pair *pair : buckets) {
if (pair != nullptr) {
entrySet.push_back(pair);
pairSet.push_back(pair);
}
}
return entrySet;
return pairSet;
}
/* 获取所有键 */
vector<int> keySet() {
vector<int> keySet;
for (Entry *pair : buckets) {
for (Pair *pair : buckets) {
if (pair != nullptr) {
keySet.push_back(pair->key);
}
@@ -91,7 +91,7 @@ class ArrayHashMap {
/* 获取所有值 */
vector<string> valueSet() {
vector<string> valueSet;
for (Entry *pair : buckets) {
for (Pair *pair : buckets) {
if (pair != nullptr) {
valueSet.push_back(pair->val);
}
@@ -101,7 +101,7 @@ class ArrayHashMap {
/* 打印哈希表 */
void print() {
for (Entry *kv : entrySet()) {
for (Pair *kv : pairSet()) {
cout << kv->key << " -> " << kv->val << endl;
}
}
@@ -135,7 +135,7 @@ int main() {
/* 遍历哈希表 */
cout << "\n遍历键值对 Key->Value" << endl;
for (auto kv : map.entrySet()) {
for (auto kv : map.pairSet()) {
cout << kv->key << " -> " << kv->val << endl;
}
@@ -0,0 +1,149 @@
/**
* File: hash_map_chaining.cpp
* Created Time: 2023-06-13
* Author: Krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* 键值对 */
struct Pair {
public:
int key;
string val;
Pair(int key, string val) {
this->key = key;
this->val = val;
}
};
/* 链式地址哈希表 */
class HashMapChaining {
private:
int size; // 键值对数量
int capacity; // 哈希表容量
double loadThres; // 触发扩容的负载因子阈值
int extendRatio; // 扩容倍数
vector<vector<Pair *>> buckets; // 桶数组
public:
/* 构造方法 */
HashMapChaining() : size(0), capacity(4), loadThres(2.0 / 3), extendRatio(2) {
buckets.resize(capacity);
}
/* 哈希函数 */
int hashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
double loadFactor() {
return (double)size / (double)capacity;
}
/* 查询操作 */
string get(int key) {
int index = hashFunc(key);
// 遍历桶,若找到 key 则返回对应 val
for (Pair *pair : buckets[index]) {
if (pair->key == key) {
return pair->val;
}
}
// 若未找到 key 则返回 nullptr
return nullptr;
}
/* 添加操作 */
void put(int key, string val) {
// 当负载因子超过阈值时,执行扩容
if (loadFactor() > loadThres) {
extend();
}
int index = hashFunc(key);
// 遍历桶,若遇到指定 key ,则更新对应 val 并返回
for (Pair *pair : buckets[index]) {
if (pair->key == key) {
pair->val = val;
return;
}
}
// 若无该 key ,则将键值对添加至尾部
buckets[index].push_back(new Pair(key, val));
size++;
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
auto &bucket = buckets[index];
// 遍历桶,从中删除键值对
for (int i = 0; i < bucket.size(); i++) {
if (bucket[i]->key == key) {
Pair *tmp = bucket[i];
bucket.erase(bucket.begin() + i); // 从中删除键值对
delete tmp; // 释放内存
size--;
return;
}
}
}
/* 扩容哈希表 */
void extend() {
// 暂存原哈希表
vector<vector<Pair *>> bucketsTmp = buckets;
// 初始化扩容后的新哈希表
capacity *= extendRatio;
buckets.clear();
buckets.resize(capacity);
size = 0;
// 将键值对从原哈希表搬运至新哈希表
for (auto &bucket : bucketsTmp) {
for (Pair *pair : bucket) {
put(pair->key, pair->val);
}
}
}
/* 打印哈希表 */
void print() {
for (auto &bucket : buckets) {
cout << "[";
for (Pair *pair : bucket) {
cout << pair->key << " -> " << pair->val << ", ";
}
cout << "]\n";
}
}
};
/* Driver Code */
int main() {
/* 初始化哈希表 */
HashMapChaining map = HashMapChaining();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
cout << "\n添加完成后,哈希表为\nKey -> Value" << endl;
map.print();
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
string name = map.get(13276);
cout << "\n输入学号 13276 ,查询到姓名 " << name << endl;
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.remove(12836);
cout << "\n删除 12836 后,哈希表为\nKey -> Value" << endl;
map.print();
return 0;
}
@@ -0,0 +1,166 @@
/**
* File: hash_map_open_addressing.cpp
* Created Time: 2023-06-13
* Author: Krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* 键值对 */
struct Pair {
int key;
string val;
Pair(int k, string v) : key(k), val(v) {
}
};
/* 开放寻址哈希表 */
class HashMapOpenAddressing {
private:
int size; // 键值对数量
int capacity; // 哈希表容量
double loadThres; // 触发扩容的负载因子阈值
int extendRatio; // 扩容倍数
vector<Pair *> buckets; // 桶数组
Pair *removed; // 删除标记
public:
/* 构造方法 */
HashMapOpenAddressing() {
// 构造方法
size = 0;
capacity = 4;
loadThres = 2.0 / 3.0;
extendRatio = 2;
buckets = vector<Pair *>(capacity, nullptr);
removed = new Pair(-1, "-1");
}
/* 哈希函数 */
int hashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
double loadFactor() {
return static_cast<double>(size) / capacity;
}
/* 查询操作 */
string get(int key) {
int index = hashFunc(key);
// 线性探测,从 index 开始向后遍历
for (int i = 0; i < capacity; i++) {
// 计算桶索引,越过尾部返回头部
int j = (index + i) % capacity;
// 若遇到空桶,说明无此 key ,则返回 nullptr
if (buckets[j] == nullptr)
return nullptr;
// 若遇到指定 key ,则返回对应 val
if (buckets[j]->key == key && buckets[j] != removed)
return buckets[j]->val;
}
return nullptr;
}
/* 添加操作 */
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] == nullptr || 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] == nullptr)
return;
// 若遇到指定 key ,则标记删除并返回
if (buckets[j]->key == key) {
delete buckets[j]; // 释放内存
buckets[j] = removed;
size -= 1;
return;
}
}
}
/* 扩容哈希表 */
void extend() {
// 暂存原哈希表
vector<Pair *> bucketsTmp = buckets;
// 初始化扩容后的新哈希表
capacity *= extendRatio;
buckets = vector<Pair *>(capacity, nullptr);
size = 0;
// 将键值对从原哈希表搬运至新哈希表
for (Pair *pair : bucketsTmp) {
if (pair != nullptr && pair != removed) {
put(pair->key, pair->val);
}
}
}
/* 打印哈希表 */
void print() {
for (auto &pair : buckets) {
if (pair != nullptr) {
cout << pair->key << " -> " << pair->val << endl;
} else {
cout << "nullptr" << endl;
}
}
}
};
/* Driver Code */
int main() {
/* 初始化哈希表 */
HashMapOpenAddressing map = HashMapOpenAddressing();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
cout << "\n添加完成后,哈希表为\nKey -> Value" << endl;
map.print();
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
string name = map.get(13276);
cout << "\n输入学号 13276 ,查询到姓名 " << name << endl;
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.remove(16750);
cout << "\n删除 16750 后,哈希表为\nKey -> Value" << endl;
map.print();
return 0;
}
@@ -68,11 +68,11 @@ public class GraphAdjList {
/* 打印邻接表 */
public void print() {
Console.WriteLine("邻接表 =");
foreach (KeyValuePair<Vertex, List<Vertex>> entry in adjList) {
foreach (KeyValuePair<Vertex, List<Vertex>> pair in adjList) {
List<int> tmp = new List<int>();
foreach (Vertex vertex in entry.Value)
foreach (Vertex vertex in pair.Value)
tmp.Add(vertex.val);
Console.WriteLine(entry.Key.val + ": [" + string.Join(", ", tmp) + "],");
Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],");
}
}
}
+14 -14
View File
@@ -7,10 +7,10 @@
namespace hello_algo.chapter_hashing;
/* 键值对 int->string */
class Entry {
class Pair {
public int key;
public string val;
public Entry(int key, string val) {
public Pair(int key, string val) {
this.key = key;
this.val = val;
}
@@ -18,7 +18,7 @@ class Entry {
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
private List<Entry?> buckets;
private List<Pair?> buckets;
public ArrayHashMap() {
// 初始化数组,包含 100 个桶
buckets = new();
@@ -36,14 +36,14 @@ class ArrayHashMap {
/* 查询操作 */
public string? get(int key) {
int index = hashFunc(key);
Entry? pair = buckets[index];
Pair? pair = buckets[index];
if (pair == null) return null;
return pair.val;
}
/* 添加操作 */
public void put(int key, string val) {
Entry pair = new Entry(key, val);
Pair pair = new Pair(key, val);
int index = hashFunc(key);
buckets[index] = pair;
}
@@ -56,19 +56,19 @@ class ArrayHashMap {
}
/* 获取所有键值对 */
public List<Entry> entrySet() {
List<Entry> entrySet = new();
foreach (Entry? pair in buckets) {
public List<Pair> pairSet() {
List<Pair> pairSet = new();
foreach (Pair? pair in buckets) {
if (pair != null)
entrySet.Add(pair);
pairSet.Add(pair);
}
return entrySet;
return pairSet;
}
/* 获取所有键 */
public List<int> keySet() {
List<int> keySet = new();
foreach (Entry? pair in buckets) {
foreach (Pair? pair in buckets) {
if (pair != null)
keySet.Add(pair.key);
}
@@ -78,7 +78,7 @@ class ArrayHashMap {
/* 获取所有值 */
public List<string> valueSet() {
List<string> valueSet = new();
foreach (Entry? pair in buckets) {
foreach (Pair? pair in buckets) {
if (pair != null)
valueSet.Add(pair.val);
}
@@ -87,7 +87,7 @@ class ArrayHashMap {
/* 打印哈希表 */
public void print() {
foreach (Entry kv in entrySet()) {
foreach (Pair kv in pairSet()) {
Console.WriteLine(kv.key + " -> " + kv.val);
}
}
@@ -123,7 +123,7 @@ public class array_hash_map {
/* 遍历哈希表 */
Console.WriteLine("\n遍历键值对 Key->Value");
foreach (Entry kv in map.entrySet()) {
foreach (Pair kv in map.pairSet()) {
Console.WriteLine(kv.key + " -> " + kv.val);
}
Console.WriteLine("\n单独遍历键 Key");
+15 -15
View File
@@ -4,16 +4,16 @@
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 键值对 int -> String */
class Entry {
/* 键值对 */
class Pair {
int key;
String val;
Entry(this.key, this.val);
Pair(this.key, this.val);
}
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
late List<Entry?> _buckets;
late List<Pair?> _buckets;
ArrayHashMap() {
// 初始化数组,包含 100 个桶
@@ -29,7 +29,7 @@ class ArrayHashMap {
/* 查询操作 */
String? get(int key) {
final int index = _hashFunc(key);
final Entry? pair = _buckets[index];
final Pair? pair = _buckets[index];
if (pair == null) {
return null;
}
@@ -38,7 +38,7 @@ class ArrayHashMap {
/* 添加操作 */
void put(int key, String val) {
final Entry pair = Entry(key, val);
final Pair pair = Pair(key, val);
final int index = _hashFunc(key);
_buckets[index] = pair;
}
@@ -50,20 +50,20 @@ class ArrayHashMap {
}
/* 获取所有键值对 */
List<Entry> entrySet() {
List<Entry> entrySet = [];
for (final Entry? pair in _buckets) {
List<Pair> pairSet() {
List<Pair> pairSet = [];
for (final Pair? pair in _buckets) {
if (pair != null) {
entrySet.add(pair);
pairSet.add(pair);
}
}
return entrySet;
return pairSet;
}
/* 获取所有键 */
List<int> keySet() {
List<int> keySet = [];
for (final Entry? pair in _buckets) {
for (final Pair? pair in _buckets) {
if (pair != null) {
keySet.add(pair.key);
}
@@ -74,7 +74,7 @@ class ArrayHashMap {
/* 获取所有值 */
List<String> values() {
List<String> valueSet = [];
for (final Entry? pair in _buckets) {
for (final Pair? pair in _buckets) {
if (pair != null) {
valueSet.add(pair.val);
}
@@ -84,7 +84,7 @@ class ArrayHashMap {
/* 打印哈希表 */
void printHashMap() {
for (final Entry kv in entrySet()) {
for (final Pair kv in pairSet()) {
print("${kv.key} -> ${kv.val}");
}
}
@@ -118,7 +118,7 @@ void main() {
/* 遍历哈希表 */
print("\n遍历键值对 Key->Value");
map.entrySet().forEach((kv) => print("${kv.key} -> ${kv.val}"));
map.pairSet().forEach((kv) => print("${kv.key} -> ${kv.val}"));
print("\n单独遍历键 Key");
map.keySet().forEach((key) => print("$key"));
print("\n单独遍历值 Value");
+7 -7
View File
@@ -6,21 +6,21 @@ package chapter_hashing
import "fmt"
/* 键值对 int->String */
type entry struct {
/* 键值对 */
type pair struct {
key int
val string
}
/* 基于数组简易实现的哈希表 */
type arrayHashMap struct {
buckets []*entry
buckets []*pair
}
/* 初始化哈希表 */
func newArrayHashMap() *arrayHashMap {
// 初始化数组,包含 100 个桶
buckets := make([]*entry, 100)
buckets := make([]*pair, 100)
return &arrayHashMap{buckets: buckets}
}
@@ -42,7 +42,7 @@ func (a *arrayHashMap) get(key int) string {
/* 添加操作 */
func (a *arrayHashMap) put(key int, val string) {
pair := &entry{key: key, val: val}
pair := &pair{key: key, val: val}
index := a.hashFunc(key)
a.buckets[index] = pair
}
@@ -55,8 +55,8 @@ func (a *arrayHashMap) remove(key int) {
}
/* 获取所有键对 */
func (a *arrayHashMap) entrySet() []*entry {
var pairs []*entry
func (a *arrayHashMap) pairSet() []*pair {
var pairs []*pair
for _, pair := range a.buckets {
if pair != nil {
pairs = append(pairs, pair)
@@ -36,7 +36,7 @@ func TestArrayHashMap(t *testing.T) {
/* 遍历哈希表 */
fmt.Println("\n遍历键值对 Key->Value")
for _, kv := range mapp.entrySet() {
for _, kv := range mapp.pairSet() {
fmt.Println(kv.key, " -> ", kv.val)
}
@@ -71,11 +71,11 @@ class GraphAdjList {
/* 打印邻接表 */
public void print() {
System.out.println("邻接表 =");
for (Map.Entry<Vertex, List<Vertex>> entry : adjList.entrySet()) {
for (Map.Entry<Vertex, List<Vertex>> pair : adjList.entrySet()) {
List<Integer> tmp = new ArrayList<>();
for (Vertex vertex : entry.getValue())
for (Vertex vertex : pair.getValue())
tmp.add(vertex.val);
System.out.println(entry.getKey().val + ": " + tmp + ",");
System.out.println(pair.getKey().val + ": " + tmp + ",");
}
}
}
+15 -15
View File
@@ -8,12 +8,12 @@ package chapter_hashing;
import java.util.*;
/* 键值对 int->String */
class Entry {
/* 键值对 */
class Pair {
public int key;
public String val;
public Entry(int key, String val) {
public Pair(int key, String val) {
this.key = key;
this.val = val;
}
@@ -21,7 +21,7 @@ class Entry {
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
private List<Entry> buckets;
private List<Pair> buckets;
public ArrayHashMap() {
// 初始化数组,包含 100 个桶
@@ -40,7 +40,7 @@ class ArrayHashMap {
/* 查询操作 */
public String get(int key) {
int index = hashFunc(key);
Entry pair = buckets.get(index);
Pair pair = buckets.get(index);
if (pair == null)
return null;
return pair.val;
@@ -48,7 +48,7 @@ class ArrayHashMap {
/* 添加操作 */
public void put(int key, String val) {
Entry pair = new Entry(key, val);
Pair pair = new Pair(key, val);
int index = hashFunc(key);
buckets.set(index, pair);
}
@@ -61,19 +61,19 @@ class ArrayHashMap {
}
/* 获取所有键值对 */
public List<Entry> entrySet() {
List<Entry> entrySet = new ArrayList<>();
for (Entry pair : buckets) {
public List<Pair> pairSet() {
List<Pair> pairSet = new ArrayList<>();
for (Pair pair : buckets) {
if (pair != null)
entrySet.add(pair);
pairSet.add(pair);
}
return entrySet;
return pairSet;
}
/* 获取所有键 */
public List<Integer> keySet() {
List<Integer> keySet = new ArrayList<>();
for (Entry pair : buckets) {
for (Pair pair : buckets) {
if (pair != null)
keySet.add(pair.key);
}
@@ -83,7 +83,7 @@ class ArrayHashMap {
/* 获取所有值 */
public List<String> valueSet() {
List<String> valueSet = new ArrayList<>();
for (Entry pair : buckets) {
for (Pair pair : buckets) {
if (pair != null)
valueSet.add(pair.val);
}
@@ -92,7 +92,7 @@ class ArrayHashMap {
/* 打印哈希表 */
public void print() {
for (Entry kv : entrySet()) {
for (Pair kv : pairSet()) {
System.out.println(kv.key + " -> " + kv.val);
}
}
@@ -126,7 +126,7 @@ public class array_hash_map {
/* 遍历哈希表 */
System.out.println("\n遍历键值对 Key->Value");
for (Entry kv : map.entrySet()) {
for (Pair kv : map.pairSet()) {
System.out.println(kv.key + " -> " + kv.val);
}
System.out.println("\n单独遍历键 Key");
@@ -0,0 +1,157 @@
/**
* File: hash_map_chaining.java
* Created Time: 2023-06-13
* Author: Krahets (krahets@163.com)
*/
package chapter_hashing;
import java.util.ArrayList;
import java.util.List;
/* 键值对 */
class Pair {
public int key;
public String val;
public Pair(int key, String val) {
this.key = key;
this.val = val;
}
}
/* 链式地址哈希表 */
class HashMapChaining {
int size; // 键值对数量
int capacity; // 哈希表容量
double loadThres; // 触发扩容的负载因子阈值
int extendRatio; // 扩容倍数
List<List<Pair>> buckets; // 桶数组
/* 构造方法 */
public HashMapChaining() {
size = 0;
capacity = 4;
loadThres = 2 / 3.0;
extendRatio = 2;
buckets = new ArrayList<>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.add(new ArrayList<>());
}
}
/* 哈希函数 */
int hashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
double loadFactor() {
return (double) size / capacity;
}
/* 查询操作 */
String get(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets.get(index);
// 遍历桶,若找到 key 则返回对应 val
for (Pair pair : 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.get(index);
// 遍历桶,若遇到指定 key ,则更新对应 val 并返回
for (Pair pair : bucket) {
if (pair.key == key) {
pair.val = val;
return;
}
}
// 若无该 key ,则将键值对添加至尾部
Pair pair = new Pair(key, val);
bucket.add(pair);
size++;
}
/* 删除操作 */
void remove(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets.get(index);
// 遍历桶,从中删除键值对
for (Pair pair : bucket) {
if (pair.key == key)
bucket.remove(pair);
}
size--;
}
/* 扩容哈希表 */
void extend() {
// 暂存原哈希表
List<List<Pair>> bucketsTmp = buckets;
// 初始化扩容后的新哈希表
capacity *= extendRatio;
buckets = new ArrayList<>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.add(new ArrayList<>());
}
size = 0;
// 将键值对从原哈希表搬运至新哈希表
for (List<Pair> bucket : bucketsTmp) {
for (Pair pair : bucket) {
put(pair.key, pair.val);
}
}
}
/* 打印哈希表 */
void print() {
for (List<Pair> bucket : buckets) {
List<String> res = new ArrayList<>();
for (Pair pair : bucket) {
res.add(pair.key + " -> " + pair.val);
}
System.out.println(res);
}
}
}
public class hash_map_chaining {
public static void main(String[] args) {
/* 初始化哈希表 */
HashMapChaining map = new HashMapChaining();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
System.out.println("\n添加完成后,哈希表为\nKey -> Value");
map.print();
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
String name = map.get(13276);
System.out.println("\n输入学号 13276 ,查询到姓名 " + name);
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.remove(12836);
System.out.println("\n删除 12836 后,哈希表为\nKey -> Value");
map.print();
}
}
@@ -0,0 +1,165 @@
/**
* File: hash_map_chaining.java
* Created Time: 2023-06-13
* Author: Krahets (krahets@163.com)
*/
package chapter_hashing;
/* 键值对 */
class Pair {
public int key;
public String val;
public Pair(int key, String val) {
this.key = key;
this.val = val;
}
}
/* 开放寻址哈希表 */
class HashMapOpenAddressing {
private int size; // 键值对数量
private int capacity; // 哈希表容量
private double loadThres; // 触发扩容的负载因子阈值
private int extendRatio; // 扩容倍数
private Pair[] buckets; // 桶数组
private Pair removed; // 删除标记
/* 构造方法 */
public HashMapOpenAddressing() {
size = 0;
capacity = 4;
loadThres = 2.0 / 3.0;
extendRatio = 2;
buckets = new Pair[capacity];
removed = new Pair(-1, "-1");
}
/* 哈希函数 */
public int hashFunc(int key) {
return key % capacity;
}
/* 负载因子 */
public double loadFactor() {
return (double) size / capacity;
}
/* 查询操作 */
public 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;
}
/* 添加操作 */
public 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;
}
}
}
/* 删除操作 */
public 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;
}
}
}
/* 扩容哈希表 */
public void extend() {
// 暂存原哈希表
Pair[] bucketsTmp = buckets;
// 初始化扩容后的新哈希表
capacity *= extendRatio;
buckets = new Pair[capacity];
size = 0;
// 将键值对从原哈希表搬运至新哈希表
for (Pair pair : bucketsTmp) {
if (pair != null && pair != removed) {
put(pair.key, pair.val);
}
}
}
/* 打印哈希表 */
public void print() {
for (Pair pair : buckets) {
if (pair != null) {
System.out.println(pair.key + " -> " + pair.val);
} else {
System.out.println("null");
}
}
}
}
public class hash_map_open_addressing {
public static void main(String[] args) {
/* 初始化哈希表 */
HashMapOpenAddressing map = new HashMapOpenAddressing();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
System.out.println("\n添加完成后,哈希表为\nKey -> Value");
map.print();
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
String name = map.get(13276);
System.out.println("\n输入学号 13276 ,查询到姓名 " + name);
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.remove(16750);
System.out.println("\n删除 16750 后,哈希表为\nKey -> Value");
map.print();
}
}
@@ -5,7 +5,7 @@
*/
/* 键值对 Number -> String */
class Entry {
class Pair {
constructor(key, val) {
this.key = key;
this.val = val;
@@ -28,15 +28,15 @@ class ArrayHashMap {
/* 查询操作 */
get(key) {
let index = this.#hashFunc(key);
let entry = this.#buckets[index];
if (entry === null) return null;
return entry.val;
let pair = this.#buckets[index];
if (pair === null) return null;
return pair.val;
}
/* 添加操作 */
set(key, val) {
let index = this.#hashFunc(key);
this.#buckets[index] = new Entry(key, val);
this.#buckets[index] = new Pair(key, val);
}
/* 删除操作 */
@@ -81,10 +81,10 @@ class ArrayHashMap {
/* 打印哈希表 */
print() {
let entrySet = this.entries();
for (const entry of entrySet) {
if (!entry) continue;
console.info(`${entry.key} -> ${entry.val}`);
let pairSet = this.entries();
for (const pair of pairSet) {
if (!pair) continue;
console.info(`${pair.key} -> ${pair.val}`);
}
}
}
@@ -115,9 +115,9 @@ map.print();
/* 遍历哈希表 */
console.info('\n遍历键值对 Key->Value');
for (const entry of map.entries()) {
if (!entry) continue;
console.info(entry.key + ' -> ' + entry.val);
for (const pair of map.entries()) {
if (!pair) continue;
console.info(pair.key + ' -> ' + pair.val);
}
console.info('\n单独遍历键 Key');
for (const key of map.keys()) {
+10 -10
View File
@@ -5,8 +5,8 @@ Author: msk397 (machangxinq@gmail.com)
"""
class Entry:
"""键值对 int->String"""
class Pair:
"""键值对"""
def __init__(self, key: int, val: str):
self.key = key
@@ -19,7 +19,7 @@ class ArrayHashMap:
def __init__(self):
"""构造方法"""
# 初始化数组,包含 100 个桶
self.buckets: list[Entry | None] = [None] * 100
self.buckets: list[Pair | None] = [None] * 100
def hash_func(self, key: int) -> int:
"""哈希函数"""
@@ -29,26 +29,26 @@ class ArrayHashMap:
def get(self, key: int) -> str:
"""查询操作"""
index: int = self.hash_func(key)
pair: Entry = self.buckets[index]
pair: Pair = self.buckets[index]
if pair is None:
return None
return pair.val
def put(self, key: int, val: str) -> None:
def put(self, key: int, val: str):
"""添加操作"""
pair = Entry(key, val)
pair = Pair(key, val)
index: int = self.hash_func(key)
self.buckets[index] = pair
def remove(self, key: int) -> None:
def remove(self, key: int):
"""删除操作"""
index: int = self.hash_func(key)
# 置为 None ,代表删除
self.buckets[index] = None
def entry_set(self) -> list[Entry]:
def entry_set(self) -> list[Pair]:
"""获取所有键值对"""
result: list[Entry] = []
result: list[Pair] = []
for pair in self.buckets:
if pair is not None:
result.append(pair)
@@ -70,7 +70,7 @@ class ArrayHashMap:
result.append(pair.val)
return result
def print(self) -> None:
def print(self):
"""打印哈希表"""
for pair in self.buckets:
if pair is not None:
@@ -0,0 +1,119 @@
"""
File: hash_map_chaining.py
Created Time: 2023-06-13
Author: Krahets (krahets@163.com)
"""
class Pair:
"""键值对"""
def __init__(self, key: int, val: str):
self.key = key
self.val = val
class HashMapChaining:
"""链式地址哈希表"""
def __init__(self):
"""构造方法"""
self.size = 0 # 键值对数量
self.capacity = 4 # 哈希表容量
self.load_thres = 2 / 3 # 触发扩容的负载因子阈值
self.extend_ratio = 2 # 扩容倍数
self.buckets = [[] for _ in range(self.capacity)] # 桶数组
def hash_func(self, key: int) -> int:
"""哈希函数"""
return key % self.capacity
def load_factor(self) -> float:
"""负载因子"""
return self.size / self.capacity
def get(self, key: int) -> str:
"""查询操作"""
index = self.hash_func(key)
bucket = self.buckets[index]
# 遍历桶,若找到 key 则返回对应 val
for pair in bucket:
if pair.key == key:
return pair.val
# 若未找到 key 则返回 None
return None
def put(self, key: int, val: str):
"""添加操作"""
# 当负载因子超过阈值时,执行扩容
if self.load_factor() > self.load_thres:
self.extend()
index = self.hash_func(key)
bucket = self.buckets[index]
# 遍历桶,若遇到指定 key ,则更新对应 val 并返回
for pair in bucket:
if pair.key == key:
pair.val = val
return
# 若无该 key ,则将键值对添加至尾部
pair = Pair(key, val)
bucket.append(pair)
self.size += 1
def remove(self, key: int):
"""删除操作"""
index = self.hash_func(key)
bucket = self.buckets[index]
# 遍历桶,从中删除键值对
for pair in bucket:
if pair.key == key:
bucket.remove(pair)
self.size -= 1
return
def extend(self):
"""扩容哈希表"""
# 暂存原哈希表
buckets = self.buckets
# 初始化扩容后的新哈希表
self.capacity *= self.extend_ratio
self.buckets = [[] for _ in range(self.capacity)]
self.size = 0
# 将键值对从原哈希表搬运至新哈希表
for bucket in buckets:
for pair in bucket:
self.put(pair.key, pair.val)
def print(self):
"""打印哈希表"""
for bucket in self.buckets:
res = []
for pair in bucket:
res.append(str(pair.key) + " -> " + pair.val)
print(res)
"""Driver Code"""
if __name__ == "__main__":
# 测试代码
hashmap = HashMapChaining()
# 添加操作
# 在哈希表中添加键值对 (key, value)
hashmap.put(12836, "小哈")
hashmap.put(15937, "小啰")
hashmap.put(16750, "小算")
hashmap.put(13276, "小法")
hashmap.put(10583, "小鸭")
print("\n添加完成后,哈希表为\n[Key1 -> Value1, Key2 -> Value2, ...]")
hashmap.print()
# 查询操作
# 向哈希表输入键 key ,得到值 value
name = hashmap.get(13276)
print("\n输入学号 13276 ,查询到姓名 " + name)
# 删除操作
# 在哈希表中删除键值对 (key, value)
hashmap.remove(12836)
print("\n删除 12836 后,哈希表为\n[Key1 -> Value1, Key2 -> Value2, ...]")
hashmap.print()
@@ -0,0 +1,132 @@
"""
File: hash_map_open_addressing.py
Created Time: 2023-06-13
Author: Krahets (krahets@163.com)
"""
class Pair:
"""键值对"""
def __init__(self, key: int, val: str):
self.key = key
self.val = val
class HashMapOpenAddressing:
"""开放寻址哈希表"""
def __init__(self):
"""构造方法"""
self.size = 0 # 键值对数量
self.capacity = 4 # 哈希表容量
self.load_thres = 2 / 3 # 触发扩容的负载因子阈值
self.extend_ratio = 2 # 扩容倍数
self.buckets: list[Pair | None] = [None] * self.capacity # 桶数组
self.removed = Pair(-1, "-1") # 删除标记
def hash_func(self, key: int) -> int:
"""哈希函数"""
return key % self.capacity
def load_factor(self) -> float:
"""负载因子"""
return self.size / self.capacity
def get(self, key: int) -> str:
"""查询操作"""
index = self.hash_func(key)
# 线性探测,从 index 开始向后遍历
for i in range(self.capacity):
# 计算桶索引,越过尾部返回头部
j = (index + i) % self.capacity
# 若遇到空桶,说明无此 key ,则返回 None
if self.buckets[j] is None:
return None
# 若遇到指定 key ,则返回对应 val
if self.buckets[j].key == key and self.buckets[j] != self.removed:
return self.buckets[j].val
def put(self, key: int, val: str):
"""添加操作"""
# 当负载因子超过阈值时,执行扩容
if self.load_factor() > self.load_thres:
self.extend()
index = self.hash_func(key)
# 线性探测,从 index 开始向后遍历
for i in range(self.capacity):
# 计算桶索引,越过尾部返回头部
j = (index + i) % self.capacity
# 若遇到空桶、或带有删除标记的桶,则将键值对放入该桶
if self.buckets[j] in [None, self.removed]:
self.buckets[j] = Pair(key, val)
self.size += 1
return
# 若遇到指定 key ,则更新对应 val
if self.buckets[j].key == key:
self.buckets[j].val = val
return
def remove(self, key: int):
"""删除操作"""
index = self.hash_func(key)
# 线性探测,从 index 开始向后遍历
for i in range(self.capacity):
# 计算桶索引,越过尾部返回头部
j = (index + i) % self.capacity
# 若遇到空桶,说明无此 key ,则直接返回
if self.buckets[j] is None:
return
# 若遇到指定 key ,则标记删除并返回
if self.buckets[j].key == key:
self.buckets[j] = self.removed
self.size -= 1
return
def extend(self):
"""扩容哈希表"""
# 暂存原哈希表
buckets_tmp = self.buckets
# 初始化扩容后的新哈希表
self.capacity *= self.extend_ratio
self.buckets = [None] * self.capacity
self.size = 0
# 将键值对从原哈希表搬运至新哈希表
for pair in buckets_tmp:
if pair not in [None, self.removed]:
self.put(pair.key, pair.val)
def print(self) -> None:
"""打印哈希表"""
for pair in self.buckets:
if pair is not None:
print(pair.key, "->", pair.val)
else:
print("None")
"""Driver Code"""
if __name__ == "__main__":
# 测试代码
hashmap = HashMapOpenAddressing()
# 添加操作
# 在哈希表中添加键值对 (key, val)
hashmap.put(12836, "小哈")
hashmap.put(15937, "小啰")
hashmap.put(16750, "小算")
hashmap.put(13276, "小法")
hashmap.put(10583, "小鸭")
print("\n添加完成后,哈希表为\nKey -> Value")
hashmap.print()
# 查询操作
# 向哈希表输入键 key ,得到值 val
name = hashmap.get(13276)
print("\n输入学号 13276 ,查询到姓名 " + name)
# 删除操作
# 在哈希表中删除键值对 (key, val)
hashmap.remove(16750)
print("\n删除 16750 后,哈希表为\nKey -> Value")
hashmap.print()
+13 -13
View File
@@ -5,14 +5,14 @@
*/
#[derive(Debug, Clone)]
/* 键值对 int->String */
pub struct Entry {
/* 键值对 */
pub struct Pair {
pub key: i32,
pub val: String,
}
/* 基于数组简易实现的哈希表 */
pub struct ArrayHashMap { buckets: Vec<Option<Entry>> }
pub struct ArrayHashMap { buckets: Vec<Option<Pair>> }
impl ArrayHashMap {
pub fn new() -> ArrayHashMap {
@@ -28,13 +28,13 @@ impl ArrayHashMap {
/* 查询操作 */
pub fn get(&self, key: i32) -> Option<&String> {
let index = self.hash_func(key);
self.buckets[index].as_ref().map(|entry| &entry.val)
self.buckets[index].as_ref().map(|pair| &pair.val)
}
/* 添加操作 */
pub fn put(&mut self, key: i32, val: &str) {
let index = self.hash_func(key);
self.buckets[index] = Some(Entry {
self.buckets[index] = Some(Pair {
key,
val: val.to_string(),
});
@@ -47,24 +47,24 @@ impl ArrayHashMap {
}
/* 获取所有键值对 */
pub fn entry_set(&self) -> Vec<&Entry> {
self.buckets.iter().filter_map(|entry| entry.as_ref()).collect()
pub fn entry_set(&self) -> Vec<&Pair> {
self.buckets.iter().filter_map(|pair| pair.as_ref()).collect()
}
/* 获取所有键 */
pub fn key_set(&self) -> Vec<&i32> {
self.buckets.iter().filter_map(|entry| entry.as_ref().map(|entry| &entry.key)).collect()
self.buckets.iter().filter_map(|pair| pair.as_ref().map(|pair| &pair.key)).collect()
}
/* 获取所有值 */
pub fn value_set(&self) -> Vec<&String> {
self.buckets.iter().filter_map(|entry| entry.as_ref().map(|entry| &entry.val)).collect()
self.buckets.iter().filter_map(|pair| pair.as_ref().map(|pair| &pair.val)).collect()
}
/* 打印哈希表 */
pub fn print(&self) {
for entry in self.entry_set() {
println!("{} -> {}", entry.key, entry.val);
for pair in self.entry_set() {
println!("{} -> {}", pair.key, pair.val);
}
}
}
@@ -95,8 +95,8 @@ fn main() {
/* 遍历哈希表 */
println!("\n遍历键值对 Key->Value");
for entry in map.entry_set() {
println!("{} -> {}", entry.key, entry.val);
for pair in map.entry_set() {
println!("{} -> {}", pair.key, pair.val);
}
println!("\n单独遍历键 Key");
@@ -72,12 +72,12 @@ public class GraphAdjList {
/* */
public func print() {
Swift.print("邻接表 =")
for entry in adjList {
for pair in adjList {
var tmp: [Int] = []
for vertex in entry.value {
for vertex in pair.value {
tmp.append(vertex.val)
}
Swift.print("\(entry.key.val): \(tmp),")
Swift.print("\(pair.key.val): \(tmp),")
}
}
}
@@ -4,8 +4,8 @@
* Author: nuomi1 (nuomi1@qq.com)
*/
/* int->String */
class Entry {
/* */
class Pair {
var key: Int
var val: String
@@ -17,7 +17,7 @@ class Entry {
/* */
class ArrayHashMap {
private var buckets: [Entry?] = []
private var buckets: [Pair?] = []
init() {
// 100
@@ -41,7 +41,7 @@ class ArrayHashMap {
/* */
func put(key: Int, val: String) {
let pair = Entry(key: key, val: val)
let pair = Pair(key: key, val: val)
let index = hashFunc(key: key)
buckets[index] = pair
}
@@ -54,14 +54,14 @@ class ArrayHashMap {
}
/* */
func entrySet() -> [Entry] {
var entrySet: [Entry] = []
func pairSet() -> [Pair] {
var pairSet: [Pair] = []
for pair in buckets {
if let pair = pair {
entrySet.append(pair)
pairSet.append(pair)
}
}
return entrySet
return pairSet
}
/* */
@@ -88,8 +88,8 @@ class ArrayHashMap {
/* */
func print() {
for entry in entrySet() {
Swift.print("\(entry.key) -> \(entry.val)")
for pair in pairSet() {
Swift.print("\(pair.key) -> \(pair.val)")
}
}
}
@@ -124,8 +124,8 @@ enum _ArrayHashMap {
/* */
print("\n遍历键值对 Key->Value")
for entry in map.entrySet() {
print("\(entry.key) -> \(entry.val)")
for pair in map.pairSet() {
print("\(pair.key) -> \(pair.val)")
}
print("\n单独遍历键 Key")
for key in map.keySet() {
@@ -5,7 +5,7 @@
*/
/* 键值对 Number -> String */
class Entry {
class Pair {
public key: number;
public val: string;
@@ -17,7 +17,7 @@ class Entry {
/* 基于数组简易实现的哈希表 */
class ArrayHashMap {
private readonly buckets: (Entry | null)[];
private readonly buckets: (Pair | null)[];
constructor() {
// 初始化数组,包含 100 个桶
@@ -32,15 +32,15 @@ class ArrayHashMap {
/* 查询操作 */
public get(key: number): string | null {
let index = this.hashFunc(key);
let entry = this.buckets[index];
if (entry === null) return null;
return entry.val;
let pair = this.buckets[index];
if (pair === null) return null;
return pair.val;
}
/* 添加操作 */
public set(key: number, val: string) {
let index = this.hashFunc(key);
this.buckets[index] = new Entry(key, val);
this.buckets[index] = new Pair(key, val);
}
/* 删除操作 */
@@ -51,8 +51,8 @@ class ArrayHashMap {
}
/* 获取所有键值对 */
public entries(): (Entry | null)[] {
let arr: (Entry | null)[] = [];
public entries(): (Pair | null)[] {
let arr: (Pair | null)[] = [];
for (let i = 0; i < this.buckets.length; i++) {
if (this.buckets[i]) {
arr.push(this.buckets[i]);
@@ -85,10 +85,10 @@ class ArrayHashMap {
/* 打印哈希表 */
public print() {
let entrySet = this.entries();
for (const entry of entrySet) {
if (!entry) continue;
console.info(`${entry.key} -> ${entry.val}`);
let pairSet = this.entries();
for (const pair of pairSet) {
if (!pair) continue;
console.info(`${pair.key} -> ${pair.val}`);
}
}
}
@@ -119,9 +119,9 @@ map.print();
/* 遍历哈希表 */
console.info('\n遍历键值对 Key->Value');
for (const entry of map.entries()) {
if (!entry) continue;
console.info(entry.key + ' -> ' + entry.val);
for (const pair of map.entries()) {
if (!pair) continue;
console.info(pair.key + ' -> ' + pair.val);
}
console.info('\n单独遍历键 Key');
for (const key of map.keys()) {
+9 -9
View File
@@ -5,13 +5,13 @@
const std = @import("std");
const inc = @import("include");
// 键值对 int->String
const Entry = struct {
// 键值对
const Pair = struct {
key: usize = undefined,
val: []const u8 = undefined,
pub fn init(key: usize, val: []const u8) Entry {
return Entry {
pub fn init(key: usize, val: []const u8) Pair {
return Pair {
.key = key,
.val = val,
};
@@ -57,7 +57,7 @@ pub fn ArrayHashMap(comptime T: type) type {
// 添加操作
pub fn put(self: *Self, key: usize, val: []const u8) !void {
var pair = Entry.init(key, val);
var pair = Pair.init(key, val);
var index = hashFunc(key);
self.buckets.?.items[index] = pair;
}
@@ -70,7 +70,7 @@ pub fn ArrayHashMap(comptime T: type) type {
}
// 获取所有键值对
pub fn entrySet(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| {
if (item == null) continue;
@@ -101,7 +101,7 @@ pub fn ArrayHashMap(comptime T: type) type {
// 打印哈希表
pub fn print(self: *Self) !void {
var entry_set = try self.entrySet();
var entry_set = try self.pairSet();
defer entry_set.deinit();
for (entry_set.items) |item| {
std.debug.print("{} -> {s}\n", .{item.key, item.val});
@@ -113,7 +113,7 @@ pub fn ArrayHashMap(comptime T: type) type {
// Driver Code
pub fn main() !void {
// 初始化哈希表
var map = ArrayHashMap(Entry){};
var map = ArrayHashMap(Pair){};
try map.init(std.heap.page_allocator);
defer map.deinit();
@@ -140,7 +140,7 @@ pub fn main() !void {
// 遍历哈希表
std.debug.print("\n遍历键值对 Key->Value\n", .{});
var entry_set = try map.entrySet();
var entry_set = try map.pairSet();
for (entry_set.items) |kv| {
std.debug.print("{} -> {s}\n", .{kv.key, kv.val});
}