0%

381. Insert Delete GetRandom O(1) - Duplicates allowed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class RandomizedCollection {
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. */
bool insert(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. */
bool remove(int val) {
if (!m.count(val)) return false;
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中删掉!!
return true;
}

/** Get a random element from the collection. */
int getRandom() {
return v.empty() ? 0 : v[rand() % v.size()].first;
}

unordered_map<int, vector<int>> m; // 添加删除O(1)所以要用unordered容器,unordered_map可保存更多信息,这里对应每个key存v中所有该key的下标
vector<pair<int, int>> v; // 数组不是只存val,还要存val所在m中的下标集合的下标,即m[v[i].first][v[i].second] = i,v[i].first是val,v[i].second是m[val]对应的数组的下标,通过该下标可以得到val在v中的下标,这么做是因为每次删除以后被修改的数在m中的下标数组不一定是有序的
};

/**
* 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();
*/

抛开题目,根据权重(个数)返回value的另一种方法是手撸一个支持dup的bst,每个node包含左右子树+自身的权重和,利用230. Kth Smallest Element in a BST的followup的思路,找指定node即可