10 lines C++ 92ms

  • 0

    unordered_set, 92ms

    class RandomizedSet {
        /** Initialize your data structure here. */
        RandomizedSet() {}
        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        bool insert(int val) {
            if(s.count(val)) return false;
            return true;
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        bool remove(int val) {
            if(!s.count(val)) return false;
            return true;
        /** Get a random element from the set. */
        int getRandom() {
            auto p = s.begin();
            advance(p, rand() % s.size());
            return *p;

Log in to reply

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