Design HashMap LeetCode solution in C++

1
class MyHashMap {
2
vector<vector<pair<int, int>>> map;
3
const int size = 10000;
4

5
public:
6
/** Initialize your data structure here. */
7
MyHashMap() {
8
map.resize(size);
9
}
10

11
/** value will always be non-negative. */
12
void put(int key, int value) {
13
int index = key % size;
14
vector<pair<int, int>> &row = map[index];
15
for (auto iter = row.begin(); iter != row.end(); iter++) {
16
if (iter->first == key) {
17
iter->second = value;
18
return;
19
}
20
}
21
row.push_back(make_pair(key, value));
22
}
23

24
/** Returns the value to which the specified key is mapped, or -1 if this map
25
* contains no mapping for the key */
26
int get(int key) {
27
int index = key % size;
28
vector<pair<int, int>> &row = map[index];
29
for (auto iter = row.begin(); iter != row.end(); iter++) {
30
if (iter->first == key) {
31
return iter->second;
32
}
33
}
34
return -1;
35
}
36

37
/** Removes the mapping of the specified value key if this map contains a
38
* mapping for the key */
39
void remove(int key) {
40
int index = key % size;
41
vector<pair<int, int>> &row = map[index];
42
for (auto iter = row.begin(); iter != row.end(); iter++) {
43
if (iter->first == key) {
44
row.erase(iter);
45
return;
46
}
47
}
48
}
49
};
50

51
/**
52
* Your MyHashMap object will be instantiated and called as such:
53
* MyHashMap* obj = new MyHashMap();
54
* obj->put(key,value);
55
* int param_2 = obj->get(key);
56
* obj->remove(key);
57
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0