classRandomizedSet{public://存储元素的值
vector<int> nums;//记录每个元素对应在nums中的索引
unordered_map<int,int> valToIndex;/** 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){if(valToIndex.count(val)){returnfalse;}//若val不存在,插入到nums尾部,并记录val对应的索引值
valToIndex[val]= nums.size();
nums.push_back(val);returntrue;}/** Removes a value from the set. Returns true if the set contained the specified element. */boolremove(int val){//若val不存在,不用再删除if(!valToIndex.count(val)){returnfalse;}//先拿到val的所有int index = valToIndex[val];//将最后一个元素的索引修改成index
valToIndex[nums.back()]= index;//交换元素swap(nums[index], nums.back());//删除最后一个元素
nums.pop_back();//删除元素val对应的索引
valToIndex.erase(val);returntrue;}/** Get a random element from the set. */intgetRandom(){return nums[rand()% nums.size()];}};