zoukankan      html  css  js  c++  java
  • leetcode 381 Insert Delete GetRandom O(1)

    class RandomizedCollection {
        unordered_map<int,unordered_set<int>> m;
        vector<int> vals;
    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) {
            bool flag=true;
            if(!m[val].empty()) flag=false;
            m[val].insert(vals.size());
            vals.push_back(val);
            return flag;
        }
        
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        bool remove(int val) {
            auto& vpos=m[val];
            if(vpos.empty()) return false;
            int pos=*vpos.begin();
            vpos.erase(vpos.begin());
            if(pos==vals.size()-1) {vals.pop_back();return true;}
            swap(vals[pos],vals[vals.size()-1]);
            m[vals[pos]].erase(vals.size()-1);
            m[vals[pos]].insert(pos);
            vals.pop_back();
            return true;
        }
        
        /** Get a random element from the collection. */
        int getRandom() {
            if(vals.empty()) return 0;
            int pos=random()%vals.size();
            return vals[pos];
            
        }
    };
    
    /**
     * Your RandomizedCollection object will be instantiated and called as such:
     * RandomizedCollection* obj = new RandomizedCollection();
     * bool param_1 = obj->insert(val);
     * bool param_2 = obj->remove(val);
     * int param_3 = obj->getRandom();
     */
  • 相关阅读:
    开发周记
    开发日记03
    开发日记01
    MVC实例应用
    MVC概述
    23种设计模式简述
    xx系统属性分析
    淘宝网质量属性
    架构漫谈阅读笔记
    浅谈软件架构师工作流程
  • 原文地址:https://www.cnblogs.com/LiuQiujie/p/12604048.html
Copyright © 2011-2022 走看看