Insert Delete GetRandom O(1) - Medium - L

1 minute read

Published:

Question

  • https://leetcode.com/problems/insert-delete-getrandom-o1/

Implement the RandomizedSet class:

RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

Approach

  • Maps and Vector

Solution

class RandomizedSet {
public:
    
    map<int, int> m;
    vector<int> v;
    
    /** Initialize your data structure here. */
    RandomizedSet() {
        m.clear();
        v.clear();
    }
    
    /** 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()){
            m.insert(make_pair(val, v.size()));
            v.push_back(val);
            return true;
        }
        return false;
    }
    
    /** 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;
        }
        if(v.size()>1){
        int in = m[val];
        m.erase(val);
        int temp=v[v.size()-1];
        v[v.size()-1]=v[in];
        v[in]=temp;
        v.pop_back();
        m[v[in]]=in;
        } else{
            m.clear();
            v.clear();
        }
        return true;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        int random_index = rand() % v.size();
        return v[random_index];
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */