和上一个题基本一样,把添加一个数改成添加一对pair就行
class MyHashMap {
public:
vector<list<pair<int, int>>> mp;
const int base = 769;
int hash(int key) {
return key % base;
}
/** Initialize your data structure here. */
MyHashMap() {
mp = vector<list<pair<int, int>>>(base);
}
/** value will always be non-negative. */
void put(int key, int value) {
int n = hash(key);
for (auto it = mp[n].begin(); it != mp[n].end(); it++) {
if ((*it).first == key) {
(*it).second = value;
return;
}
}
mp[n].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 n = hash(key);
for (auto it = mp[n].begin(); it != mp[n].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 n = hash(key);
for (auto it = mp[n].begin(); it != mp[n].end(); it++) {
if ((*it).first == key) {
mp[n].erase(it);
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);
*/