2024每日刷题(127)
Leetcode—706. 设计哈希映射
数组实现代码
class MyHashMap {
public:MyHashMap() {memset(arr, -1, sizeof(arr));}void put(int key, int value) {arr[key] = value;}int get(int key) {if(arr[key] == -1) {return -1;} return arr[key];}void remove(int key) {arr[key] = -1;}
private:int arr[1000001];
};/*** 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);*/
运行结果
链地址法实现代码
class MyHashMap {
public:MyHashMap(): lists(kSize) {}void put(int key, int value) {auto &pairs = lists[key % kSize];for(auto &[k, v] : pairs) {if(k == key) {v = value;return;}}pairs.emplace_back(key, value);}int get(int key) {auto &pairs = lists[key % kSize];for(auto &[k, v] : pairs) {if(k == key) {return v;}}return -1;}void remove(int key) {auto &pairs = lists[key % kSize];for(auto it = pairs.begin(); it != pairs.end(); it++) {if(it->first == key) {pairs.erase(it);return;}}}
private:static constexpr int kSize = 10000;vector<list<pair<int, int>>> lists;
};/*** 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);*/
运行结果
constexpr
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!