Wednesday, October 9, 2019

Insert Delete GetRandom O(1)



class RandomizedSet {
private:
    set<int> st;
    int counter;
public:
    /** Initialize your data structure here. */
    RandomizedSet() {
        counter = 0;
    }
   
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if (st.count(val)) {
            return false;
        }
        st.insert(val);
        counter++;
        return true;
    }
   
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if (st.count(val) == 0) {
            return false;
        }
        st.erase(val);
        counter--;
        return true;
    }
   
    /** Get a random element from the set. */
    int getRandom() {
       
        set<int>::iterator it = st.begin();
        int random = rand() % counter;
        while (random-- != 0) {
            it++;
        }
        return *it;
    }
};

/**
 * 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();
 */

===========
private: vector<int> v; unordered_map<int, int> m;

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { //cout << m.size() << endl; //print(); if (m.count(val) != 0) return false; v.push_back(val); m[val] = v.size()-1; //print(); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { // print(); if (m.count(val) == 0) return false; int idx = m[val]; v[idx] = v.back(); m[v[idx]] = idx; m.erase(val); v.pop_back(); //print(); return true; } /** Get a random element from the set. */ int getRandom() { int idx = std::rand() % v.size(); //std::cout << idx << std::endl; return v[idx]; }

No comments:

Post a Comment