381. Insert Delete GetRandom O(1) - Duplicates allowed

来源:互联网 发布:如何查看淘宝产品排名 编辑:程序博客网 时间:2024/05/22 12:01

使用unordered_map和unordered_set存取

class RandomizedCollection {public:    /** Initialize your data structure here. */    RandomizedCollection() {        mp.clear();    }        /** 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(mp.find(val)!=mp.end())            flag=false;        vec.push_back(val);        mp[val].insert(vec.size()-1);        return flag;    }        /** Removes a value from the collection. Returns true if the collection contained the specified element. */    bool remove(int val) {        if(mp.find(val)==mp.end())            return false;        unordered_set<int>::iterator it=mp[val].begin();        if(vec[vec.size()-1]!=val)        {            int tail=vec[vec.size()-1];            vec[*it]=tail;            mp[tail].erase(vec.size()-1);            mp[tail].insert(*it);        }        vec.pop_back();                mp[val].erase(*it);        if(mp[val].size()==0)            mp.erase(val);        return true;    }        /** Get a random element from the collection. */    int getRandom() {        return vec[rand()%vec.size()];    }private:    unordered_map<int,unordered_set<int>> mp;    vector<int> vec;};/** * 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(); */


0 0