zoukankan      html  css  js  c++  java
  • 381 Insert Delete GetRandom 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();
    详见:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
    C++:

    class RandomizedCollection {
    public:
        /** Initialize your data structure here. */
        RandomizedCollection() {}
        
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        bool insert(int val) {
            m[val].insert(nums.size());
            nums.push_back(val);
            return m[val].size() == 1;
        }
        
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        bool remove(int val) {
            if (m[val].empty())
            {
                return false;
            }
            int idx = *m[val].begin();
            m[val].erase(idx);
            if (nums.size() - 1 != idx) 
            {
                int t = nums.back();
                nums[idx] = t;
                m[t].erase(nums.size() - 1);
                m[t].insert(idx);
            } 
            nums.pop_back();
            return true;
        }
        
        /** Get a random element from the collection. */
        int getRandom() {
            return nums[rand() % nums.size()];
        }
    
    private:
        vector<int> nums;
        unordered_map<int, unordered_set<int>> m;
    };
    

      参考:http://www.cnblogs.com/grandyang/p/5756148.html

  • 相关阅读:
    luogu P3128 [USACO15DEC]最大流Max Flow (树上差分)
    codeforces 600E . Lomsat gelral (线段树合并)
    bzoj 1483: [HNOI2009]梦幻布丁 (链表启发式合并)
    bzoj 1257: [CQOI2007]余数之和 (数学+分块)
    codevs 2606 约数和问题 (数学+分块)
    bzoj 2038: [2009国家集训队]小Z的袜子(hose) (莫队)
    bzoj 1086: [SCOI2005]王室联邦 (分块+dfs)
    bzoj 4542: [Hnoi2016]大数 (莫队)
    【NOIp模拟赛】Tourist Attractions
    【NOIp模拟赛】String Master
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8848869.html
Copyright © 2011-2022 走看看