O(1) 时间插入、删除和获取随机元素 - 允许重复

设计一个支持在平均 时间复杂度 O(1) , 执行以下操作的数据结构。

注意: 允许出现重复元素。

  1. insert(val):向集合中插入元素 val。
  2. remove(val):当 val 存在时,从集合中移除一个 val。
  3. 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();
//维护一个list存储所有val的值
//维护一个map存储每个val在List的位置
//随机只需要再list随机
//删除操作是将所要删除的数将在list中最后一个位置的数放到所要删除的位置
//在更新一下最有一个数在map中的位置即可
class RandomizedCollection {

    private Map<Integer,Set<Integer>> map  ;

    private List<Integer> list ;

    private Random random  ;

    private int size = 0 ;


    public RandomizedCollection() {
        map = new HashMap<>() ;
        list = new ArrayList<>() ;
        random = new Random() ;
    }

    public boolean insert(int val) {
        if(map.containsKey(val)){
            Set<Integer> indexes = map.get(val) ;
            list.add(size,val) ;
            indexes.add(size) ;
            size++ ;
            return false ;
        }else{
            Set<Integer> indexes = new HashSet<>() ;
            map.put(val,indexes) ;
            list.add(size,val) ;
            indexes.add(size) ;
            size++ ;
            return true ;
        }
    }

    public boolean remove(int val) {
        if(!map.containsKey(val)){
            return false ;
        }
        Set<Integer> indexes = map.get(val) ;
        if(list.get(size-1) == val){
            indexes.remove(size-1) ;
            size-- ;
        }else{
            Iterator<Integer> it = indexes.iterator() ;
            int index = it.next() ;
            it.remove();
            int last = list.get(size-1) ;
            list.set(index,last) ;
            Set<Integer> set = map.get(last) ;
            set.remove(size-1) ;
            set.add(index) ;
            size-- ;
        }
        if(indexes.size() == 0){
            map.remove(val) ;
        }
        return true ;
    }

    public int getRandom() {
        return list.get(random.nextInt(size));
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值