C++ solution using unordered_multiset

  • -1
    class RandomizedCollection {
        /** 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 ret = st.find(val)==st.end();
            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;
            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.