Skip to content

Commit b107ea3

Browse files
committed
leetcode
1 parent 26eef9c commit b107ea3

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class MyHashSet {
2+
vector<vector<int> *> set;
3+
const int size = 500;
4+
public:
5+
/** Initialize your data structure here. */
6+
MyHashSet() {
7+
set.resize(size);
8+
}
9+
10+
void add(int key) {
11+
const int index = key % size;
12+
if (!contains(key))
13+
{
14+
auto v = set[index];
15+
if (v == nullptr)
16+
{
17+
v = new vector<int>;
18+
}
19+
v->push_back(key);
20+
set[index] = v;
21+
}
22+
}
23+
24+
void remove(int key) {
25+
const int index = key % size;
26+
auto v = set[index];
27+
if (v == nullptr) return;
28+
for (auto iter = v->begin(); iter != v->end(); iter++)
29+
{
30+
if (*iter == key)
31+
{
32+
v->erase(iter);
33+
return;
34+
}
35+
}
36+
}
37+
38+
/** Returns true if this set contains the specified element */
39+
bool contains(int key) {
40+
const int index = key % size;
41+
const auto v = set[index];
42+
if (v == nullptr) return false;
43+
for (auto e : *v)
44+
{
45+
if (e == key)
46+
{
47+
return true;
48+
}
49+
}
50+
return false;
51+
}
52+
};

0 commit comments

Comments
 (0)