leetcode 381.Insert Delete GetRandom

时间:2023-03-09 16:28:52
leetcode 381.Insert Delete GetRandom

这道题中要求使用O(1)的方法来删除和插入元素的,那么首先需要寻找到对应的元素,这个可以使用map的O(1)的查询时间的,然后是删除对应的元素的,那么可以根据 堆排序中类似的做法把最后面的元素插入到前面来并且置换掉对应的值的。

class RandomizedCollection {
public:
/** Initialize your data structure here. */
RandomizedCollection() { } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
m[val].insert(num.size());
num.push_back(val);
return m[val].size()==;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(m[val].empty()) return false;
int pos=*m[val].begin();
m[val].erase(pos);
if(pos!=num.size()-){
int temp=num.back();
num[pos]=temp;
m[temp].erase(num.size()-);
m[temp].insert(pos);
}
num.pop_back();
return true;
} /** Get a random element from the collection. */
int getRandom() {
return num[rand()%num.size()];
}
private:
vector<int> num;
map<int, set<int>> m;
}; /**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/