-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_0706_MyHashMap.cc
More file actions
65 lines (56 loc) · 1.06 KB
/
Problem_0706_MyHashMap.cc
File metadata and controls
65 lines (56 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <list>
#include <vector>
using namespace std;
class MyHashMap
{
// 链地址法
vector<list<pair<int, int>>> memory;
static const int PRIM = 1021;
int hash(int value) { return value % PRIM; }
public:
MyHashMap() : memory(PRIM) {}
void put(int key, int value)
{
int hk = hash(key);
for (auto& e : memory[hk])
{
if (e.first == key)
{
e.second = value;
return;
}
}
memory[hk].push_back({key, value});
}
int get(int key)
{
int hk = hash(key);
for (auto& e : memory[hk])
{
if (e.first == key)
{
return e.second;
}
}
return -1;
}
void remove(int key)
{
int hk = hash(key);
for (auto itr = memory[hk].begin(); itr != memory[hk].end(); ++itr)
{
if (itr->first == key)
{
memory[hk].erase(itr);
break;
}
}
}
};
/**
* 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);
*/