class RandomizedCollection { public: typedef std::unordered_multimap<int,int> intmap; /** 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) { // cout<<"insert: --------"<<val<<endl; if(mm.count(val) == 0) { v.push_back(val); mm.insert(pair<int,int>(val,v.size()-1)); return true; } else { v.push_back(val); mm.insert(pair<int,int>(val,v.size()-1)); return false; } } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) {
if(mm.count(val) == 0) { return false; } else { auto range = mm.equal_range(val); auto one_val = range.first; int val_pos = one_val->second; if(val_pos == v.size()-1) { v.pop_back(); mm.erase(one_val); return true; } else { int back = v.back(); int back_pos = v.size()-1; v.pop_back(); auto back_range = mm.equal_range(back); auto back_range_it = back_range.first; for(; back_range_it != back_range.second;back_range_it++) { if(back_range_it->second == back_pos) { break; } } mm.erase(one_val); }
return true; } } /** Get a random element from the collection. */ int getRandom() { return v[rand()%v.size()]; } unordered_multimap<int,int>mm; vector<int>v; };
/** * 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(); */