The question link - https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
The code has 2 multisets, S1 takes insertion and deletion into account, S2 only takes deletion into account and vector a only takes insertion into account.
In insertion, the element is added into S1 and a. It returns true or false depending if element already present in S1 or not.
In deletion, the element if present in S1, is inserted into S2 and deleted from S1. It returns true or false, depending on whether if already present in S1 or not.
In random function, we get the index of range [0, a.size()-1]. A new multiset s3 is assigned equal to S2. We check if the element is present in s3 and if it is, we delete from there. If it's not and it's not present in s1, we loop again. If it is present in s1, we return the val.
class RandomizedCollection {
public:
multiset<int> s1, s2; // s2 contains all the deleted elements
vector<int> a; // a contains all the elements pushed till now
RandomizedCollection() { // initialization function
}
bool insert(int val) {
if(s1.find(val) == s1.end()) {
s1.insert(val);
a.push_back(val);
return true;
}
s1.insert(val);
a.push_back(val);
return false;
}
bool remove(int val) {
auto it = s1.find(val);
if(it == s1.end()) {
return false;
}
s1.erase(it);
s2.insert(val); // adding the deleted value to s2
return true;
}
int getRandom() {
multiset<int> s3 = s2; // assigning s3 to s2
while(1) {
int id = rand()%(a.size());
auto it = s3.find(a[id]);
if(it!=s3.end()) { // if the random value is present in s3, delete from there
s3.erase(it);
} else if(s1.find(a[id])!=s1.end()){
return a[id];
}
}
}
};
Aucun commentaire:
Enregistrer un commentaire