Skip to content

Commit 5e52ea6

Browse files
authored
Merge pull request #2098 from kabirdhillon7/380Swift
Created 0380-Insert-Delete-GetRandom-O(1).Swift
2 parents 3c13908 + e2e8cbd commit 5e52ea6

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class RandomizedSet {
2+
var random = Set<Int>()
3+
4+
init() {
5+
6+
}
7+
8+
func insert(_ val: Int) -> Bool {
9+
if !random.contains(val){
10+
random.insert(val)
11+
return true
12+
} else {
13+
return false
14+
}
15+
}
16+
17+
func remove(_ val: Int) -> Bool {
18+
if random.contains(val) {
19+
random.remove(val)
20+
return true
21+
} else {
22+
return false
23+
}
24+
}
25+
26+
func getRandom() -> Int {
27+
return random.randomElement()!
28+
}
29+
}
30+
31+
/**
32+
* Your RandomizedSet object will be instantiated and called as such:
33+
* let obj = RandomizedSet()
34+
* let ret_1: Bool = obj.insert(val)
35+
* let ret_2: Bool = obj.remove(val)
36+
* let ret_3: Int = obj.getRandom()
37+
*/

0 commit comments

Comments
 (0)