#### 题目

Design a data structure that supports all following operations in average O(1) time.

`insert(val)`: Inserts an item val to the set if not already present.

`remove(val)`: Removes an item val from the set if present.

`getRandom`: Returns a random element from current set of elements. Each element must have the same probability of being returned.

#### 思路

``````class RandomizedSet {

var set: Set<Int>
/** Initialize your data structure here. */
init() {
self.set = Set<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 set.contains(val) {
return false
} else {
set.insert(val)
return true
}
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
func remove(_ val: Int) -> Bool {
if set.contains(val) {
set.remove(val)
return true
} else {
return false
}
}

/** Get a random element from the set. */
func getRandom() -> Int {
let offset = Int.random(in: 0..<set.count)

// if older than swift 4.2
// let offset = randomInt(min: 0, max: set.count - 1)

let index = set.index(set.startIndex, offsetBy: offset)
return set[index]
}

//before swift 4.2
func randomInt(min: Int, max: Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}

}
``````

``````//TODO
...
``````