leetcode 381 Insert Delete GetRandom O - Duplicates allowed

Posted liuqiujie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 381 Insert Delete GetRandom O - Duplicates allowed相关的知识,希望对你有一定的参考价值。

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();
 */

 

以上是关于leetcode 381 Insert Delete GetRandom O - Duplicates allowed的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 381. Insert Delete GetRandom O - Duplicates allowed (插入删除和获得随机数 常数时间 允许重复项)

381. Insert Delete GetRandom O - Duplicates allowed

381. Insert Delete GetRandom O - Duplicates allowed

381. Insert Delete GetRandom O - Duplicates allowed - Hard

381 Insert Delete GetRandom O - Duplicates allowed O 时间插入删除和获取随机元素 - 允许重复

LeetCode 0381. O 时间插入删除和获取随机元素 - 允许重复