C++ solution 89 percentile


  • 0
    G
    class RandomizedSet {
    
    private:
    
        unordered_map<int,int> M;
        vector<int> S;
        default_random_engine Gen;
    
    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(M.find(val) != M.end())
            {
                return (false);
            }
            
            S.push_back(val);
            M[val] = S.size() - 1;
            return (true);
        }
        
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        bool remove(int val) 
        {
            if(M.find(val) == M.end())
            {
                return (false);
            }
            
            swap(S[M[val]],S[S.size() - 1]);
            M[S[M[val]]] = M[val];
            S.pop_back();
            M.erase(val);
            return (true);
            
        }
        
        /** Get a random element from the set. */
        int getRandom() 
        {
            uniform_int_distribution<int> Dist(0,S.size() - 1);
            return S[Dist(Gen)];
        }
    };

Log in to reply
 

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