@@ -12,7 +12,7 @@ class RandomizedCollection {
12
12
bool insert (int val) {
13
13
bool has = used_.count (val);
14
14
15
- list_.emplace_back (val);
15
+ list_.emplace_back (val, used_[val]. size () );
16
16
used_[val].emplace_back (list_.size () - 1 );
17
17
18
18
return !has;
@@ -24,7 +24,7 @@ class RandomizedCollection {
24
24
return false ;
25
25
}
26
26
27
- used_[list_.back ()] .back () = used_[val].back ();
27
+ used_[list_.back (). first ][list_ .back (). second ] = used_[val].back ();
28
28
swap (list_[used_[val].back ()], list_.back ());
29
29
30
30
used_[val].pop_back ();
@@ -38,61 +38,14 @@ class RandomizedCollection {
38
38
39
39
/* * Get a random element from the collection. */
40
40
int getRandom () {
41
- return list_[rand () % list_.size ()];
41
+ return list_[rand () % list_.size ()]. first ;
42
42
}
43
43
44
44
private:
45
- vector<int > list_;
45
+ vector<pair< int , int > > list_;
46
46
unordered_map<int , vector<int >> used_;
47
47
};
48
48
49
-
50
- // Time: O(1)
51
- // Space: O(n)
52
- class RandomizedCollection2 {
53
- public:
54
- /* * Initialize your data structure here. */
55
- RandomizedCollection2 () {
56
-
57
- }
58
-
59
- /* * Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
60
- bool insert (int val) {
61
- bool has = used_.count (val);
62
-
63
- list_.emplace_back (val);
64
- used_.emplace (val, list_.size () - 1 );
65
-
66
- return !has;
67
- }
68
-
69
- /* * Removes a value from the collection. Returns true if the collection contained the specified element. */
70
- bool remove (int val) {
71
- if (!used_.count (val)) {
72
- return false ;
73
- }
74
-
75
- auto it_to_delete = used_.find (val);
76
- auto it_to_back = used_.find (list_.back ());
77
- it_to_back->second = it_to_delete->second ;
78
- swap (list_[it_to_delete->second ], list_.back ());
79
-
80
- used_.erase (it_to_delete);
81
- list_.pop_back ();
82
-
83
- return true ;
84
- }
85
-
86
- /* * Get a random element from the collection. */
87
- int getRandom () {
88
- return list_[rand () % list_.size ()];
89
- }
90
-
91
- private:
92
- vector<int > list_;
93
- unordered_multimap<int , int > used_;
94
- };
95
-
96
49
/* *
97
50
* Your RandomizedCollection object will be instantiated and called as such:
98
51
* RandomizedCollection obj = new RandomizedCollection();
0 commit comments