java笔试--数据结构模拟

 相关题目:

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开始编辑,持续更新

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值