-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0705-design-hashset.ts
65 lines (50 loc) · 1.35 KB
/
0705-design-hashset.ts
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class _ListNode { // ListNode has a confict
key: number;
next: _ListNode | undefined;
constructor(key: number) {
this.key = key;
}
}
class MyHashSet {
readonly ARRAY_LENGTH = Math.pow(10, 4);
set = new Array<_ListNode>(this.ARRAY_LENGTH);
constructor() {
for (let i = 0; i < this.ARRAY_LENGTH; i++)
this.set[i] = new _ListNode(0);
}
add(key: number): void {
let cur = this.set[key % this.set.length];
while (cur.next) {
if (cur.next.key === key)
return;
cur = cur.next;
}
cur.next = new _ListNode(key);
}
remove(key: number): void {
let cur = this.set[key % this.set.length];
while (cur.next) {
if (cur.next.key === key) {
cur.next = cur.next.next;
return;
}
cur = cur.next;
}
}
contains(key: number): boolean {
let cur = this.set[key % this.set.length];
while (cur.next) {
if (cur.next.key === key)
return true;
cur = cur.next;
}
return false;
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* var obj = new MyHashSet()
* obj.add(key)
* obj.remove(key)
* var param_3 = obj.contains(key)
*/