Design a data structure that supports all following operations in averageO(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 (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
classRandomizedSet { private: vector<int> vc; unordered_map<int,int> mp; 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. */ boolinsert(int val){ bool hasVal = (mp.find(val) != mp.end()); if(hasVal) returnfalse; vc.push_back(val); mp.insert({val,vc.size()-1}); returntrue; } /** Removes a value from the set. Returns true if the set contained the specified element. */ boolremove(int val){ unordered_map<int, int>::iterator itVal = mp.find(val); if(itVal == mp.end()) returnfalse; unordered_map<int, int>::iterator itBack = mp.find(vc.back()); int index = itVal->second; swap(vc[index], vc.back()); swap(itBack->second, itVal->second); vc.pop_back(); mp.erase(itVal); returntrue; } /** Get a random element from the set. */ intgetRandom(){ int randomIndex = rand() % vc.size(); return vc[randomIndex]; } };
/** * 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(); */