381 Insert Delete GetRandom O(1) - Duplicates allowed
class RandomizedCollection {
public:
unordered_map<int, unordered_set<int>> vals;
vector<int> val_array;
RandomizedCollection() {
}
bool insert(int val) {
bool res = true;
if ( vals.find(val) != vals.end() ) res = false;
val_array.push_back(val);
vals[val].insert(int(val_array.size())-1);
return res;
}
bool remove(int val) {
if ( vals.find(val) == vals.end() ) return false;
int n = val_array.size();
int i = *(vals[val].begin());
if ( val_array[n-1] == val ) {
val_array.erase(val_array.begin() + n-1);
vals[val].erase(vals[val].find(n-1));
if ( vals[val].empty() ) vals.erase(vals.find(val));
return true;
}
int last = val_array[n-1];
val_array[i] = last;
auto it = vals[last].find(n-1);
vals[last].erase(it);
vals[last].insert(i);
val_array.erase(val_array.begin() + n-1);
vals[val].erase(vals[val].find(i));
if ( vals[val].empty() ) vals.erase(vals.find(val));
return true;
}
int getRandom() {
int n = val_array.size();
if ( n == 0 ) return -1;
return val_array[random()%n];
}
};