forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertDeleteGetRandom.swift
54 lines (44 loc) · 1.46 KB
/
InsertDeleteGetRandom.swift
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
/**
* Question Link: https://leetcode.com/problems/insert-delete-getrandom-o1/
* Primary idea: Using an array and dictionary since adding or removing at the end of array is constant.
* Time Complexity: O(1), Space Complexity: O(n)
*
*/
class RandomizedSet {
var numToIndex: [Int: Int]
var nums: [Int]
/** Initialize your data structure here. */
init() {
numToIndex = [Int: Int]()
nums = [Int]()
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
func insert(_ val: Int) -> Bool {
if let _ = numToIndex[val] {
return false
} else {
numToIndex[val] = nums.count
nums.append(val)
return true
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
func remove(_ val: Int) -> Bool {
if let index = numToIndex[val], let last = nums.last {
numToIndex[last] = index
numToIndex[val] = nil
nums.swapAt(index, nums.count - 1)
nums.removeLast()
return true
} else {
return false
}
}
/** Get a random element from the set. */
func getRandom() -> Int {
guard let randomElement = nums.randomElement() else {
fatalError("Empty set!")
}
return randomElement
}
}