class RandomizedSet {
private:
unordered_map<int,int> hash;//哈希實(shí)現(xiàn)刪除
vector<int> v;//動(dòng)態(tài)數(shù)組實(shí)現(xiàn)插入和隨機(jī)訪問(wèn)
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. */
//當(dāng)元素 val 不存在時(shí),向集合中插入該項(xiàng)。
bool insert(int val) {
if(hash.find(val) != hash.end()) return false; //如果集合中已經(jīng)存在val,返回false,
v.push_back(val);//否則插入到數(shù)組末尾
hash[val] = v.size() - 1;//
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
//元素 val 存在時(shí),從集合中移除該項(xiàng)。
bool remove(int val) {
if(hash.find(val) == hash.end()) return false;//如果集合中不存在val,返回false
int lastPos = v.size() - 1;//數(shù)組最后一個(gè)元素位置
int valPos = hash[val];//將被刪除值和數(shù)組最后一位進(jìn)行交換
v[valPos] = v[lastPos];
v.pop_back();//刪除
hash[v[valPos]] = valPos;//被交換的值下標(biāo)發(fā)生變化,需要更新
hash.erase(val); //哈希表中刪除val的項(xiàng)
return true;
}
/** Get a random element from the set. */
//隨機(jī)返回現(xiàn)有集合中的一項(xiàng)。每個(gè)元素應(yīng)該有相同的概率被返回。
int getRandom() {
int size = v.size();
int pos = rand() % size;//對(duì)下標(biāo)產(chǎn)生隨機(jī)數(shù)
return v[pos];//數(shù)組可以根據(jù)下表返回
}
};
/**
* 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();
*/