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:
// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();
// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);
// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);
// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);
// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();
// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);
// getRandom should return 1 and 2 both equally likely.
collection.getRandom();
解法1:
自己写的怎么都没过OA,这个AC的答案是网上抄的[捂脸]。主要的思想和没有duplicates的版本很相似。区别就是这里对于每一个数字,要存储的是出现的index的list。删除操作的时候,把末尾的元素直接写到被删除的元素的位置。同时维护一下两个index的list.
对于需要删除的数字,去掉list中相应的位置
对于末尾的数字,在list中加入要删除的数字的位置
在队列中把要删除的元素的位置置换为末尾的元素
删除队列末尾的元素(因为已经放到了队列中间去了)
C++
Java