Insert Delete GetRandom O(1)

Design a data structure that supports all following operations in average O(1) time.

insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Solution: Vector and Hash Table

insert(x): Only hash map and list are O(1)

remove(x): Only hash map and list are O(1)

search(x): Only hash map

getRandom(): Returns a random element from current set of elements

We can use hashing to support first 3 operations in O(1) time. For getRandom function, we can use a resizable array together with hashing. Resizable arrays support insert in O(1).

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 (m.count(val)) return false;
        v.push_back(val);
        m[val] = v.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.count(val) == 0) return false;
        int last = v.back();
        m[last] = m[val];
        v[m[val]] = last;
        v.pop_back();
        m.erase(val);        
        return true;
    }

    /** Get a random element from the set. */
    int getRandom() {
        int randIndex = rand() % v.size();
        return v[randIndex];
    }

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

results matching ""

    No results matching ""