题目地址:
https://leetcode.com/problems/design-hashmap/
设计HashMap。
可以用拉链法处理哈希冲突。代码如下:
class MyHashMap {
public:
using PII = pair<int, int>;
#define x first
#define y second
#define N 19997
vector<PII> h[N];
MyHashMap() {}
void put(int key, int value) {
int ha = key % N;
for (auto &[k, v] : h[ha])
if (k == key) {
v = value;
return;
}
h[ha].emplace_back(key, value);
}
int get(int key) {
int ha = key % N;
for (auto &[k, v] : h[ha]) {
if (k == key) return v;
}
return -1;
}
void remove(int key) {
int ha = key % N;
for (auto it = h[ha].begin(); it != h[ha].end(); it++)
if (it->x == key) {
h[ha].erase(it);
return;
}
}
};
时间复杂度最差会达到O ( n ) O(n)O(n)。
版权声明:本文为qq_46105170原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。