-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path381.cpp
More file actions
52 lines (46 loc) · 1.33 KB
/
381.cpp
File metadata and controls
52 lines (46 loc) · 1.33 KB
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
43
44
45
46
47
48
49
50
51
52
class RandomizedCollection {
public:
vector<int> nums;
int index = 0;
unordered_map<int, unordered_set<int>> val2idx;
RandomizedCollection() {
}
bool insert(int val) {
bool res = val2idx[val].size() == 0;
val2idx[val].insert(index);
nums.push_back(val);
index++;
return res;
}
bool remove(int val) {
bool res = val2idx[val].size() > 0;
if (!res) return res;
auto removeIdxIt = val2idx[val].begin();
int removeIdx = *removeIdxIt;
val2idx[val].erase(removeIdxIt);
index--;
if (removeIdx == index) {
nums.pop_back();
return res;
}
int exchangeIdx = index;
int exchangeVal = nums[index];
swap(nums[removeIdx], nums[exchangeIdx]);
val2idx[exchangeVal].erase(exchangeIdx);
val2idx[exchangeVal].insert(removeIdx);
nums.pop_back();
return res;
}
int getRandom() {
int n = nums.size();
int rnd = rand() % n;
return nums[rnd];
}
};
/**
* 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();
*/