/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ boolinsert(int val){ if(map.find(val) != map.end()) { returnfalse; } vector.push_back(val); map[val] = vector.size() - 1; returntrue; }
/** Removes a value from the set. Returns true if the set contained the specified element. */ boolremove(int val){ if(map.find(val) == map.end()) { returnfalse; }
int last = vector.back(); map[last] = map[val]; vector[map[last]] = last; map.erase(val); vector.pop_back(); returntrue; }
/** Get a random element from the set. */ intgetRandom(){ returnvector[rand() % vector.size()]; } };
/** * 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(); */