Question:
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.
Example:
Explanation:
很神奇的一道题,因为需要每个操作的复杂度平均为O(1),最初我只用了一个Arraylist存也AC了,但是时间很久,因为remove的时候不是O(1).换了Hashmap存index,快一些。但是要注意,remove那边不能直接count--,需要和最后一个值调换,这样保证其他的index不变,只减少最后一个。A little tricky 总而言之,算法设计还是蛮有趣的,好好想想。