classRandomizedCollection { public: /** Initialize your data structure here. */ RandomizedCollection() { srand(time(NULL)); }
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ boolinsert(int val){ bool res = m.find(val) == m.end(); m[val].push_back(v.size()); v.emplace_back(val, m[val].size() - 1); return res; }
/** Removes a value from the collection. Returns true if the collection contained the specified element. */ boolremove(int val){ if (!m.count(val)) returnfalse; m[v.back().first][v.back().second] = m[val].back(); v[m[val].back()] = v.back(); v.pop_back(); m[val].pop_back(); if (m[val].empty()) m.erase(val); // 切记如果m[val]空了要从m中删掉!! returntrue; }
/** Get a random element from the collection. */ intgetRandom(){ return v.empty() ? 0 : v[rand() % v.size()].first; }
/** * 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(); */