直接看代码,简单易懂。
class MyHashMap {
private:
vector<list<pair<int, int>>> data;
static const int base = 769;
static int hash(int key) {//哈希函数
return key % base;
}
public:
//初始化
MyHashMap() :data(base) {}
void put(int key, int value) {
int h = hash(key);
//链地址法解决哈希冲突
for (auto it = data[h].begin(); it != data[h].end(); ++it) {
if ((*it).first == key) {
(*it).second = value;
return;
}
}
data[h].emplace_back(key, value);
//data[h].push_back(make_pair(key, value));
}
int get(int key) {
int h = hash(key);
for (auto it = data[h].begin(); it != data[h].end(); ++it) {
if ((*it).first == key)
return (*it).second;
}
return -1;
}
void remove(int key) {
int h = hash(key);
for (auto it = data[h].begin(); it != data[h].end(); ++it) {
if ((*it).first == key) {
data[h].erase(it);
return;
}
}
}
};