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:
// 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();问题描述:
设计一个数据结构,支持以O(1)时间复杂度执行以下操作: 1. insert(val):向集合中插入一个元素。若集合之前无val,返回true,否则返回false。 2. remove(va):如果集合中有val,则删除val。若集合有val,返回true,否则返回false。 3. getRandom():随机返回集合中一个元素,注意返回某元素的概率与该元素在集合中的数目线性相关。
问题分析:
这题的前置问题是这道题: https://leetcode.com/problems/insert-delete-getrandom-o1/description/ 解法是: https://leetcode.com/problems/insert-delete-getrandom-o1/discuss/85401/Java-solution-using-a-HashMap-and-an-ArrayList-along-with-a-follow-up.-(131-ms)
首先要注意到,操作中并没有获取任一个元素,只是插入,删除还有随机获取元素 需要维护两个结构: 1.nums,存储元素 2.locs,存储元素对应下标
由于插入和随机获取都是O(1),解题的核心是每次删除nums尾部的元素,若被删除元素位于尾部,直接删除list和locs中对应下标,若不是,需要将删除元素与list尾部元素进行替换
