class RandomizedSet {
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. */
bool insert(int val) {
if (pos.find(val) != pos.end())
return false;
pos[val] = nums.size();
nums.push_back(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (pos.find(val) == pos.end())
return false;
int idx = pos[val];
nums[idx] = nums.back();
pos[nums[idx]] = idx;
nums.pop_back();
pos.erase(val);
return true;
}
/** Get a random element from the set. */
int getRandom() {
return nums[rand()%nums.size()];
}
private:
vector<int> nums;
unordered_map<int, int> pos;
};
//需要常数时间返回随机数,所以必须要有连续的数组
//需要很快的知道一个数有没有存在,那么就必须至少有unordered_set
//要配合删除,也就需要知道这个数在哪儿,就需要unordered_map。删除的时候采用和最后一个交换的方式来删除。因为不需要保证它们之间的顺序。