C++ solution using unordered_multiset


  • -1
    B
    class RandomizedCollection {
    public:
        /** Initialize your data structure here. */
        unordered_multiset<int>st;
        RandomizedCollection() {
            
        }
        
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        bool insert(int val) {
            bool ret = st.find(val)==st.end();
            st.insert(val);
            return ret;
        }
        
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        bool remove(int val) {
            auto it = st.find(val);
            if(it==st.end()) return false;
            st.erase(it);
            return true;
        }
        
        /** Get a random element from the collection. */
        int getRandom() {
            auto it = st.begin();
            int i = rand()%st.size();
            while(i-->0) it++;
            return *it;
        }
    };

Log in to reply
 

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