Leetcode 381 Solution

This article provides solution to leetcode question 381 (insert-delete-getrandom-o1-duplicates-allowed)

https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed

Solution

class RandomizedCollection { map<int, list<int>> m_m; vector<pair<int, int*>> m_v;
public: /** Initialize your data structure here. */ RandomizedCollection() {
}
void display() { for (auto pair : m_m) { printf("%d: ", pair.first); for (auto val : pair.second) printf("%d ", val); printf("\n"); } for (auto pair : m_v) printf("%d ", pair.first); printf("\n\n\n"); }
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { bool res = false;
if (m_m.find(val) == m_m.end()) { m_m[val] = list<int>(); res = true; }
m_m[val].push_back(m_v.size()); m_v.push_back(make_pair(val, (int*)&m_m[val].back()));
return res; }
/** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if (m_m.find(val) == m_m.end()) return false;
int index = *m_m[val].rbegin(); swap(m_v[index], m_v[m_v.size() - 1]);
m_v.pop_back(); m_m[val].pop_back(); if (m_m[val].empty()) m_m.erase(val);
*m_v[index].second = index;
return true; }
/** Get a random element from the collection. */ int getRandom() { int index = rand() % m_v.size(); return m_v[index].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(); */