Description
Design a data structure that supports all following operations in average O(1) time.
Note
Duplicate elements are allowed.
insert(val): Inserts an item val to the collection.
remove(val): Removes an item val from the collection if present.
getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.
Example
|
|
Solution
|
|
Analyse
这道题很值得细细思考,首先,为什么要用LinkedHashSet,而不是普通的set,因为HashSet不能保证插入的顺序,LinkedHashSet可以按照插入的顺序来对数据进行操作。至于为什么要保持顺序,那就是和nums对应,打一个简单的比方。