Every day a leetcode
题目来源:706. 设计哈希映射
解法1:模拟
代码:
class MyHashMap {
private:
vector<list<pair<int,int>>> HashMap;
static const int base=1009;
static int hash(int key)
{
return key%base;
}
public:
MyHashMap(): HashMap(base) {}
void put(int key, int value) {
int index=hash(key);
for(auto i=HashMap[index].begin();i!=HashMap[index].end();i++)
{
if((*i).first == key)
{
(*i).second=value;
return;
}
}
HashMap[index].push_back(make_pair(key,value));
}
int get(int key) {
int index=hash(key);
for(auto i=HashMap[index].begin();i!=HashMap[index].end();i++)
{
if((*i).first == key)
{
return (*i).second;
}
}
return -1;
}
void remove(int key) {
int index=hash(key);
for(auto i=HashMap[index].begin();i!=HashMap[index].end();i++)
{
if((*i).first == key)
{
HashMap[index].erase(i);
return;
}
}
}
};
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap* obj = new MyHashMap();
* obj->put(key,value);
* int param_2 = obj->get(key);
* obj->remove(key);
*/
结果:

复杂度分析:
时间复杂度:O(n/b),其中 n 为哈希表中的元素数量,b 为链表的数量。
空间复杂度:O(n+b)
这篇博客介绍了如何实现一个高效的哈希映射类,包括`put`、`get`和`remove`操作。使用了链表解决哈希冲突,时间复杂度为O(n/b),空间复杂度为O(n+b)。该设计考虑了哈希函数的选择和链表的遍历,适用于处理大量数据的场景。
387

被折叠的 条评论
为什么被折叠?



