Short multiset based c


  • -1
    C
    class RandomizedCollection {
    public:
        /** Initialize your data structure here. */
        multiset<int> col;
        RandomizedCollection() 
        {
            srand(time(0));
        }
        
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        bool insert(int val) 
        {
            auto itr = col.find(val);
            col.insert(val);
            return (itr == col.end()) ? true : false;
        }
        
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        bool remove(int val) 
        {
            auto itr = col.find(val);
            
            if(itr != col.end())
            {
                col.erase(itr);
                return true;
            }
            
            return false;
        }
        
        /** Get a random element from the collection. */
        int getRandom() 
        {
            int index = rand() % col.size();
            auto it = col.begin();
            advance(it, index);
            return *it;
        }
    };
    
    /**
     * 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();
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.