forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0380-insert-delete-getrandom-o1.kt
53 lines (41 loc) · 1.12 KB
/
0380-insert-delete-getrandom-o1.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
44
45
46
47
48
49
50
51
52
53
/*
* Containing the logic behind the operations, but a cleaner Kotlin solution is provided below.
* Here implement some of the logic of the functions ourselves, as in the video, to have this solution compatible with the video solution.
*/
class RandomizedSet() {
val hs = HashSet<Int>()
fun insert(`val`: Int): Boolean {
if(hs.contains(`val`))
return false
else {
hs.add(`val`)
return true
}
}
fun remove(`val`: Int): Boolean {
if(hs.contains(`val`)){
hs.remove(`val`)
return true
}else
return false
}
fun getRandom(): Int {
return hs.random()
}
}
/*
* Cleaner Kotlin solution. add() and remove()
*/
class RandomizedSet() {
val hs = HashSet<Int>()
fun insert(`val`: Int) = hs.add(`val`)
fun remove(`val`: Int) = hs.remove(`val`)
fun getRandom() = hs.random()
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* var obj = RandomizedSet()
* var param_1 = obj.insert(`val`)
* var param_2 = obj.remove(`val`)
* var param_3 = obj.getRandom()
*/