File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ class RandomizedSet {
2
+ public:
3
+ /** Initialize your data structure here. */
4
+ vector<int> v;
5
+
6
+ map<int, int> m;
7
+
8
+ RandomizedSet() {
9
+ srand(time(nullptr));
10
+ }
11
+
12
+ /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
13
+ bool insert(int val)
14
+ {
15
+
16
+ if(m.count(val))
17
+ return false;
18
+
19
+ int index = v.size();
20
+ v.push_back(val);
21
+
22
+ // and hashmap also
23
+ m[val] = index;
24
+ // m.insert(std::pair<int,int>(val, index));
25
+ return true;
26
+ }
27
+
28
+ /** Removes a value from the set. Returns true if the set contained the specified element. */
29
+ bool remove(int val)
30
+ {
31
+
32
+ if(!m.count(val))
33
+ return false;
34
+
35
+ int idx = m[val];
36
+ int last = v.back();
37
+ if(last!=val)
38
+ {
39
+ v[idx] = last;
40
+ m[last] = idx;
41
+ }
42
+ m.erase(val);
43
+ v.pop_back();
44
+ return true;
45
+ }
46
+
47
+ /** Get a random element from the set. */
48
+ int getRandom()
49
+ {
50
+ int random_idx = rand() % v.size();
51
+ return v[random_idx];
52
+ // return v[rand()%v.size()];
53
+ }
54
+ };
55
+
56
+ /**
57
+ * Your RandomizedSet object will be instantiated and called as such:
58
+ * RandomizedSet* obj = new RandomizedSet();
59
+ * bool param_1 = obj->insert(val);
60
+ * bool param_2 = obj->remove(val);
61
+ * int param_3 = obj->getRandom();
62
+ */
You can’t perform that action at this time.
0 commit comments