题目:
如果做过昨天的题目的话,今天这题就很简单。
我们知道哈希Map是一个key对应一个value,那么在昨天的基础上使用pair模板去插入这个值就好了。
访问的时候用迭代器的first和second访问
C++代码:(测试从昨天那里扒)
class MyHashMap {
public:
vector<list<pair<int, int>>> hashmap;
static const int base = 769;
static int hash(int key) {
return key % base;
}
/** Initialize your data structure here. */
MyHashMap():hashmap(base) {
}
/** value will always be non-negative. */
void put(int key, int value) {
int h = hash(key);
for(auto it = hashmap[h].begin();it!=hashmap[h].end();it++){
if((*it).first == key){
(*it).second = value;
return;
}
}
hashmap[h].push_back(make_pair(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 h = hash(key);
for(auto it = hashmap[h].begin();it!=hashmap[h].end();it++){
if((*it).first==key){
return (*it).second;
}
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
int h = hash(key);
for(auto it = hashmap[h].begin();it!=hashmap[h].end();it++){
if((*it).first==key){
hashmap[h].erase(it);
return;
}
}
}
};
多提一句,这个hashmap的初始化大小为769是必要的。因为不这么做的话,系统就会分配给你一个大小。同时,会存在两倍增长的关系,造成额外的开销。