2021/3/14,今天的每日一题是Leetcode706. 设计哈希映射,题意如下:
和昨天的设计哈希集合类似,没有看过的可以移步《[每日一题]Leetcode705. 设计哈希集合》,区别哈希映射要存的是两个值,我们可以用pair这个数据结构实现,具体代码也差不多。
c++参考代码:
class MyHashMap {
public:
vector<list<pair<int,int>>> p;
static const int mod = 977;
MyHashMap():p(mod)//初始化,防止下标越界
{}
void put(int key, int value) {
pair<int,int> now(key,value);
int n=key%mod;
for(auto it=p[n].begin();it!=p[n].end();it++)
{
if((*it).first==key)
{
(*it).second=value;
return ;
}
}
p[n].push_back(now);
}
int get(int key) {
int n=key%mod;
for(auto it=p[n].begin();it!=p[n].end();it++)
{
if((*it).first==key)
{
return (*it).second;
}
}
return -1;
}
void remove(int key) {
int n=key%mod;
for(auto it=p[n].begin();it!=p[n].end();it++)
{
if((*it).first==key)
{
p[n].erase(it);
return ;
}
}
}
};
时间复杂度:O(N/B),其中 N为哈希表中的元素数量,B 为链表的数量。假设哈希值是均匀分布的,则每个链表大概长度为N/B。
参考资料
·力扣官方题解