Skip to content

Commit 81be8ae

Browse files
authored
Create design-hashmap.cpp
1 parent 50c11dd commit 81be8ae

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

C++/design-hashmap.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Time: O(1)
2+
// Space: O(n)
3+
4+
class MyHashMap {
5+
public:
6+
/** Initialize your data structure here. */
7+
MyHashMap() : data_(10000) {
8+
9+
}
10+
11+
/** value will always be positive. */
12+
void put(int key, int value) {
13+
auto& list = data_[key % data_.size()];
14+
auto it = find_if(list.begin(), list.end(),
15+
[&](const pair<int, int>& i) { return i.first == key; } );
16+
if (it != list.end()) {
17+
it->second = value;
18+
} else {
19+
list.emplace_back(key, value);
20+
}
21+
}
22+
23+
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
24+
int get(int key) {
25+
auto& list = data_[key % data_.size()];
26+
auto it = find_if(list.begin(), list.end(),
27+
[&](const pair<int, int>& i) { return i.first == key; } );
28+
if (it != list.end()) {
29+
return it->second;
30+
} else {
31+
return -1;
32+
}
33+
}
34+
35+
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
36+
void remove(int key) {
37+
auto& list = data_[key % data_.size()];
38+
auto it = find_if(list.begin(), list.end(),
39+
[&](const pair<int, int>& i) { return i.first == key; } );
40+
if (it != list.end()) {
41+
list.erase(it);
42+
}
43+
}
44+
45+
private:
46+
vector<list<pair<int, int>>> data_;
47+
};
48+
49+
/**
50+
* Your MyHashMap object will be instantiated and called as such:
51+
* MyHashMap obj = new MyHashMap();
52+
* obj.put(key,value);
53+
* int param_2 = obj.get(key);
54+
* obj.remove(key);
55+
*/

0 commit comments

Comments
 (0)