• leetcode381- Insert Delete GetRandom O(1)


    Design a data structure that supports all following operations in average O(1) time.

    Note: Duplicate elements are allowed.

    1. insert(val): Inserts an item val to the collection.
    2. remove(val): Removes an item val from the collection if present.
    3. 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();

    算法:试了一下用双Map无法实现频率正比概率random。当然如果random的概率不和频率成正比而是等概率的话反而还真的必须得用双map。

    最后使用Map + List。和前面的区别在于Map<Integer, Set<Integer>>,维护的映射从存储单个int下标信息变成了用一个Set存储下标信息。 删的时候比较麻烦。细节不写好容易报错。

    1.删待删数对应的一个下标(如果set空了记得清空整个key)。

    2.如果之前删的下标不是最后一个,那你还要把最后一个数提到下标那里(更新该val的下标信息要一加一删,切记),然后在list里也更新一下。

    3.在List里把最后一个数删掉,size更新。返回

    实现:

    class RandomizedCollection {
        
        private List<Integer> list;
        private Map<Integer, Set<Integer>> vi;
        private int size;
        
        /** Initialize your data structure here. */
        public RandomizedCollection() {
            list = new ArrayList<Integer>();
            vi = new HashMap<Integer, Set<Integer>>();
            size = 0;
        }
        
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        public boolean insert(int val) {
            boolean contains = vi.containsKey(val);
            if (!contains) {
                vi.put(val, new LinkedHashSet<>());
            }
            vi.get(val).add(size);
            list.add(val);
            size++;
            // 注意是返回!contains!,相反的
            return !contains;
        }
        
         
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        public boolean remove(int val) {
            if (!vi.containsKey(val)) {
                return false;
            }
            
            // 删原来那个的下标
            int index = vi.get(val).iterator().next();
            vi.get(val).remove(index);
            if (vi.get(val).size() == 0) {
                vi.remove(val);
            }    
            
            // 如果需要换的话把换到前面后的下标信息更新
            if (index < size - 1) {
                int lastVal = list.get(size - 1);
                //这句不要漏了啊啊啊!更新最后一个的坐标要一加一删
                vi.get(lastVal).remove(size - 1);
                vi.get(lastVal).add(index);
                list.set(index, lastVal);    
            }
            
            list.remove(size - 1);
            
            size--;
            return true;
        }
        
        /** Get a random element from the collection. */
        public int getRandom() {
            return list.get(new Random().nextInt(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();
     */
  • 相关阅读:
    Postman初探
    web页面和本地数据对比问题
    Katalon Recorder初探
    Flask入门
    自我实现预言
    gulp 安装 依赖
    maven环境
    加解密 生成 X.509格式,DER编码,后缀名.cer。加密公钥证书
    我的魔法 公式找回中
    gulp 自动ftp至服务器时,处理开发 测试服务器地址问题
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7941692.html
Copyright © 2020-2023  润新知