380. O(1) 时间插入、删除和获取随机元素
代码如下:
cpp
class RandomizedSet {
public:
vector<int> arr;
unordered_map<int,int> m;
public:
RandomizedSet() {
}
bool insert(int val) {
if(m.find(val)!=m.end())
return false;
arr.push_back(val);
m[val]=arr.size()-1;
return true;
}
bool remove(int val) {
if(m.find(val)==m.end())
return false;
int valPos=m[val];
arr[valPos]=arr[arr.size()-1];
m[arr[valPos]]=valPos;
arr.pop_back();
m.erase(val);
return true;
}
int getRandom() {
return arr[rand()%arr.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();
*/