381. O(1) 时间插入、删除和获取随机元素 - 允许重复
设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。
注意: 允许出现重复元素。
insert(val)
:向集合中插入元素 val。remove(val)
:当 val 存在时,从集合中移除一个 val。getRandom
:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。
示例:
// 初始化一个空的集合。 RandomizedCollection collection = new RandomizedCollection(); // 向集合中插入 1 。返回 true 表示集合不包含 1 。 collection.insert(1); // 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。 collection.insert(1); // 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。 collection.insert(2); // getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。 collection.getRandom(); // 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。 collection.remove(1); // getRandom 应有相同概率返回 1 和 2 。 collection.getRandom();
这种设计题做得比较少,平时刷题大都是【给输入数据,根据一些列的规则输出期望值】这种题型,今天刚好每日一题是这一道,不会做,索性看题解,做个记录。
当时看到时间复杂度是O(1),立刻是想到是Hash,但是也就仅仅想到了Hash,后面的就卡壳了,看了官方题解之后,哦,原来用的都是一写比较常用的数据结构实现的。果然啊,将知识点由点串成线,再由线串成面是一样技术活,自己还是菜了。
下面来看一下官方题解:
代码题解:
class RandomizedCollection {
Map<Integer,Set<Integer>> idx;//key表示val,value保存的是val的下标集合
List<Integer> nums;//nums存放val
/** Initialize your data structure here. */
public RandomizedCollection() {
idx = new HashMap<Integer,Set<Integer>>();
nums = new ArrayList<Integer>();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
nums.add(val);
Set<Integer> set = idx.getOrDefault(val,new HashSet<>());
set.add(nums.size() - 1);//添加下标
idx.put(val,set);
return set.size() == 1;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if(!idx.containsKey(val)){
return false;
}
Iterator<Integer> it = idx.get(val).iterator();
int i = it.next();//第一次出现的下标
int lastNum = nums.get(nums.size() - 1);//获取列表最后一个元素
nums.set(i,lastNum);//将下标i对应的元素设置nums最后一个元素(交换)
idx.get(val).remove(i);//val对应的下标集合中删除对应的下标i
idx.get(lastNum).remove(nums.size() - 1);//删除lastNum对应的最后一个下标,因为已经调整到i
if(i < nums.size() - 1){
idx.get(lastNum).add(i);//如果i不是nums最后一个下标,则添加到lastNum对应的下标集合中
}
if(idx.get(val).size() == 0){//val不再存在
idx.remove(val);//删除val
}
nums.remove(nums.size() - 1);//删除nums最后一个元素,就是val
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
return nums.get((int)(Math.random() * nums.size()));
}
}
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/