forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
70 lines (55 loc) · 1.74 KB
/
main.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/// Source : https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
/// Author : liuyubobobo
/// Time : 2018-07-08
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/// Vector to stroe all elements
/// HashMap to restore all maps between elements and index
/// Time Complexity: O(1)
/// Space Complexity: O(n)
class RandomizedCollection {
private:
vector<int> nums;
unordered_map<int, unordered_set<int>> indexes;
public:
/** Initialize your data structure here. */
RandomizedCollection() {
nums.clear();
indexes.clear();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
nums.push_back(val);
indexes[val].insert(nums.size() - 1);
return indexes[val].size() == 1;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(indexes.find(val) != indexes.end()){
int i = *indexes[val].begin();
indexes[val].erase(i);
if(indexes[val].size() == 0)
indexes.erase(val);
int num = nums.back();
nums.pop_back();
if(!(num == val && nums.size() == i)){
nums[i] = num;
indexes[num].erase(nums.size());
indexes[num].insert(i);
}
return true;
}
return false;
}
/** Get a random element from the collection. */
int getRandom() {
int rndIndex = rand() % nums.size();
return nums[rndIndex];
}
};
int main() {
return 0;
}