题目1:实现一个简单的哈希结构 https://leetcode-cn.com/problems/design-hashmap/
使用YouLookDeliciousC的做法,即用拉链表来实现。
技巧是vector<Node*>来做为容器
struct Node {
int key;
int val;
Node* next;
Node(int _key,int _val):key(_key),val(_val),next(nullptr){}
};
int len = 1000;
class MyHashMap {
public:
//哈希表的顶底层结构
//1.哈希函数的设计
//2.哈希冲突的方法
//3.动态扩容的策略
vector<Node*> arr;
MyHashMap() {
arr = vector<Node*>(len, new Node(-1, -1));
}
void put(int key, int value) {
int bucket = key % len;
Node* cur = arr[bucket];//获取当前的桶
Node* pre = nullptr;
while (cur) {
//如果存在这个值
if (cur->key == key) {
cur->val = value;
return;
}
pre = cur;
cur = cur->next;
}
pre->next = new Node(key, value);
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int get(int key) {
int bucket = key % len;
Node* cur = arr[bucket];
while (cur) {
if (cur->key == key) {
return cur->val;
}
cur = cur->next;
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
int bucket = key % len;
Node* cur = arr[bucket];
Node* pre = nullptr;
while (cur) {
if (cur->key == key) {
pre->next = cur->next;
return;
}
pre = cur;
cur = cur->next;
}
}
};
关于哈希还有什么可以说的呢?
1.设计哈希函数(要求)
常用的哈希函数总结:
https://leetcode-cn.com/explore/learn/card/hash-table/206/practical-application-design-the-key/824/
2.防止冲突的方法:
开放寻址法
拉链法
3.装载因子
对于开放寻址法:装入的数量/数组的空间
对于拉链法:m/n