Design a data structure that supports all following operations in average O(1) time. 1,insert(val): Inserts an item val to the set if not already present. 2,remove(val): Removes an item val from the set if present. 3,getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
class RandomizedSet { public:map data_map; //数字 - 对应位置vector data;/** 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(data_map.count(val) != 0){return false;}else{data.push_back(val); //在数组中插入该值data_map[val] = data.size()-1; //在map中加入该值和数组中的位置对应return true;}}/** Removes a value from the set. Returns true if the set contained the specified element. */bool remove(int val) {//查找是是否在map中存在,如果不存在则返回falseif(data_map.count(val) == 0){return false;}else{//否则,和数组尾部数据位置交换,删除掉尾部数据int tail = data[data.size()-1];int pos1 = data_map[val]; //获取需要删除数据的位置int pos2 = data.size()-1; //最后一个元素的位置data_map[tail] = pos1;data_map[val] = pos2;data[pos1] = tail; //将需要删除的元素和尾部元素交换data_map.erase(val); //删除哈希表中的数据data.pop_back(); //删除数组中的datareturn true;}}/** Get a random element from the set. */int getRandom() {int t = data.size();int random_num = rand()%t;return data[random_num];} };