Share my Simple and Clean C++ solution.


  • 0
    F
    class RandomizedSet {
        vector<int> buffer;
        unordered_map<int, int> idx_map;
        default_random_engine rng;
    public:
        bool insert(int val) {
            if (idx_map.find(val) != idx_map.end())
                return false;
            buffer.push_back(val);
            idx_map[val] = buffer.size() - 1;
            return true;
        }
        bool remove(int val) {
            if (idx_map.find(val) == idx_map.end())
                return false;
            int idx = idx_map[val];
            buffer[idx] = buffer.back();
            idx_map[buffer.back()] = idx;
            idx_map.erase(val);
            buffer.pop_back();
            return true;
        }
        int getRandom() {
            uniform_int_distribution<int> distribution(0,buffer.size() - 1);
            int idx = distribution(rng);
            return buffer[idx];
        }
    };
    

Log in to reply
 

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