C++ 80ms solution


  • 2
    X

    class RandomizedSet {
    public:
    /** 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(umap.find(val) == umap.end()) {
            umap[val] = vec.size();
            vec.push_back(val);
            return true;
        } else {
            return false;
        }
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        auto iter = umap.find(val);
        if(iter == umap.end()) {
            return false;
        } else {
            int back = vec.back();
            if(back != val) {
                vec[umap[val]] = back;
                umap[back] = umap[val];
            }
            umap.erase(iter);
            vec.pop_back();
            return true;
        }
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        int size = vec.size();
        srand(time(0));
        return vec[rand()%size];
        
    }
    

    private:
    vector<int> vec;
    unordered_map<int, int> umap;
    };


  • 0
    N

    Maybe you should use srand() in the init.

        RandomizedSet() {
            srand(time(0));
        }
    

Log in to reply
 

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