和上一个题基本一样,把添加一个数改成添加一对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);
*/
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有