forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0706.cpp
More file actions
executable file
·51 lines (44 loc) · 973 Bytes
/
LC0706.cpp
File metadata and controls
executable file
·51 lines (44 loc) · 973 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/design-hashmap/
Time: O(n), average O(1)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class MyHashMap {
private:
int prime;
vector<list<pair<int, int>>> table;
int hash(int key) {
return key % prime;
}
list<pair<int, int>>::iterator search(int key) {
int h = hash(key);
return find_if(table[h].begin(), table[h].end(), [&key](pair<int, int>& p) {
return p.first == key;
});
}
public:
MyHashMap() : prime(10007), table(prime) {}
void put(int key, int value) {
int h = hash(key);
auto it = search(key);
if (it != table[h].end())
it->second = value;
else
table[h].emplace_back(key, value);
}
int get(int key) {
int h = hash(key);
auto it = search(key);
if (it != table[h].end())
return it->second;
else
return -1;
}
void remove(int key) {
int h = hash(key);
auto it = search(key);
if (it != table[h].end())
table[h].erase(it);
}
};