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