forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0705-design-hashset.kt
43 lines (36 loc) · 944 Bytes
/
0705-design-hashset.kt
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
class MyHashSet() {
class LN(val value: Int) {
var next: LN? = null
}
val set = Array (10000) { LN(0) }
fun add(key: Int) {
var cur = set[hash(key)]
while (cur?.next != null) {
if (cur?.next?.value == key)
return
cur = cur?.next!!
}
cur.next = LN(key)
}
fun remove(key: Int) {
var cur = set[hash(key)]
while (cur?.next != null) {
if (cur?.next?.value == key) {
cur?.next = cur?.next?.next
return
}
cur = cur?.next!!
}
}
fun contains(key: Int): Boolean {
var cur = set[hash(key)]
while (cur?.next != null) {
if (cur?.next?.value == key) {
return true
}
cur = cur?.next!!
}
return false
}
private fun hash(key: Int) = key % set.size
}