相关题目:
381. O(1) 时间插入、删除和获取随机元素 - 允许重复
1、O(1)时间插入,删除,获取随机元素--允许重复
实现思路:因为插入与删除需要O(1),则需要HashMap或者HashSet来进行实现。否则复杂度为O(N)。但是若要在有重复元素的情况下,查询的时候也需要O(1),只能为数组等顺序结构(若不包含重复元素,则直接可以用HashMap来进行实现)。所以说需要HashMap与ArrayList。但是,在删除的时候数组对某一个元素的删除为O(N),所以得需要记录每一个元素在List中的索引。所以,可以在HashMap中使用HashSet来进行存储。
class RandomizedCollection {
HashMap<Integer,HashSet<Integer>> h=null;
List<Integer> l=null;
int total=0;
/** Initialize your data structure here. */
public RandomizedCollection() {
h=new HashMap<>();
l=new ArrayList<>();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
HashSet<Integer> hs=h.getOrDefault(val,new HashSet<>());
l.add(val);
hs.add(l.size()-1);
h.put(val,hs);
return hs.size()==1;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if(!l.contains(val)){
return false;
}
Iterator<Integer> hs=h.get(val).iterator();
int index=hs.next();
int LastNum=l.get(l.size()-1);
//此时不能删除,如果删除所有的索引就会变化,只能set修改。!!!
l.set(index,LastNum);
h.get(val).remove(index);
h.get(LastNum).remove(l.size()-1);
//判断待删除的元素是否为最后一个元素,若为最后一个元素的话,就无需重新增加到hashMap中。
//只需要删除即可,若不为最后一个元素(响应l.set(index,LastNum)函数),则需要调整元素的位置得重新增加
if(index!=l.size()-1){
h.get(LastNum).add(index);
}
if(h.get(val).size()==0){
h.remove(val);
}
l.remove(l.size()-1);
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
return l.get((int)(l.size()*Math.random()));
}
}
/**
* 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();
*/
与2020/10/31开始编辑,持续更新