Skip to content

Commit 34d71fc

Browse files
authored
Update insert-delete-getrandom-o1-duplicates-allowed.cpp
1 parent b7cfbdf commit 34d71fc

File tree

1 file changed

+4
-51
lines changed

1 file changed

+4
-51
lines changed

C++/insert-delete-getrandom-o1-duplicates-allowed.cpp

+4-51
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class RandomizedCollection {
1212
bool insert(int val) {
1313
bool has = used_.count(val);
1414

15-
list_.emplace_back(val);
15+
list_.emplace_back(val, used_[val].size());
1616
used_[val].emplace_back(list_.size() - 1);
1717

1818
return !has;
@@ -24,7 +24,7 @@ class RandomizedCollection {
2424
return false;
2525
}
2626

27-
used_[list_.back()].back() = used_[val].back();
27+
used_[list_.back().first][list_.back().second] = used_[val].back();
2828
swap(list_[used_[val].back()], list_.back());
2929

3030
used_[val].pop_back();
@@ -38,61 +38,14 @@ class RandomizedCollection {
3838

3939
/** Get a random element from the collection. */
4040
int getRandom() {
41-
return list_[rand() % list_.size()];
41+
return list_[rand() % list_.size()].first;
4242
}
4343

4444
private:
45-
vector<int> list_;
45+
vector<pair<int, int>> list_;
4646
unordered_map<int, vector<int>> used_;
4747
};
4848

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-
9649
/**
9750
* Your RandomizedCollection object will be instantiated and called as such:
9851
* RandomizedCollection obj = new RandomizedCollection();

0 commit comments

Comments
 (0)