classRandomizedSet { 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){ map<int, int>::iterator it = m.find(val); if (it != m.end()) { returnfalse; } else { m[val] = arr.size(); arr.push_back(val); returntrue; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ boolremove(int val){ map<int, int>::iterator it = m.find(val); if (it != m.end()) { if (arr.size() > 1) { int idx = it->second; arr[idx] = arr[arr.size() - 1]; m[arr[arr.size() - 1]] = idx; } m.erase(it); arr.pop_back(); returntrue; } else { returnfalse; } } /** Get a random element from the set. */ intgetRandom(){ int idx = random() % arr.size(); return arr[idx]; } private: vector<int> arr; map<int, int> m; };
/** * 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(); */