381. Insert Delete GetRandom O(1) - Duplicates allowed

381. Insert Delete GetRandom O(1) - Duplicates allowedarrow-up-right

Design a data structure that supports all following operations in average O(1) time.Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.

  2. remove(val): Removes an item val from the collection if present.

  3. 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();

My Solutions:

380不能有重复数字,而这道题可以有,不能像之前那道题那样建立每个数字和其坐标的映射了,但是可以建立数字和其所有出现位置的集合之间的映射, 所以原来的那个HashMap从<值-位置>,改成<值-位置的集合>。

插入的时候,是插入到位置的集合。查询也是找到list中的随机位置。

删除的时候,同样是将ArrayList的最后一个交换到前面,但是现在一个值有多个位置,所以我们要交换对位置,不能和原来一样直接替换。

Last updated