Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4fbd191

Browse files
committed
Create: 0706-design-hashmap.cpp
1 parentcdfcdd9 commit4fbd191

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

‎cpp/0706-design-hashmap.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
Design a HashMap without using any built-in hash table libraries.
3+
4+
Designing a hash table using the chaining method, where a vector holds a list of pairs representing the key-value mappings.
5+
6+
Time: O(n)
7+
Space: O(n)
8+
*/
9+
10+
classMyHashMap {
11+
public:
12+
constint N =10010;
13+
vector<list<pair<int,int>>> h;
14+
15+
/** Initialize your data structure here.*/
16+
MyHashMap() {
17+
h = vector<list<pair<int,int>>>(N);
18+
}
19+
20+
list<pair<int,int>>::iteratorfind(int key) {
21+
int t = key % N;
22+
for (auto it = h[t].begin(); it != h[t].end(); it ++ ) {
23+
if (it->first == key)
24+
return it;
25+
}
26+
return h[t].end();
27+
}
28+
29+
/** value will always be non-negative.*/
30+
voidput(int key,int value) {
31+
auto t = key % N;
32+
auto it =find(key);
33+
if (it == h[t].end()) h[t].push_back({key, value});
34+
else it->second = value;
35+
}
36+
37+
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key*/
38+
intget(int key) {
39+
auto t = key % N;
40+
auto it =find(key);
41+
if (it != h[t].end())return it->second;
42+
return -1;
43+
}
44+
45+
/** Removes the mapping of the specified value key if this map contains a mapping for the key*/
46+
voidremove(int key) {
47+
auto t = key % N;
48+
auto it =find(key);
49+
if (it != h[t].end()) h[t].erase(it);
50+
}
51+
};
52+
53+
/**
54+
* Your MyHashMap object will be instantiated and called as such:
55+
* MyHashMap* obj = new MyHashMap();
56+
* obj->put(key,value);
57+
* int param_2 = obj->get(key);
58+
* obj->remove(key);
59+
*/

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp