Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0cf93af

Browse files
add 380
1 parent 8acaf93 commit 0cf93af

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎0380-insert-delete-getrandom-o1.cpp‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
380. Insert Delete GetRandom O(1)
3+
4+
Submitted: January 2, 2025
5+
6+
Runtime: 26 ms (beats 97.77%)
7+
Memory: 113.02 MB (beats 36.95%)
8+
*/
9+
10+
class RandomizedSet {
11+
private:
12+
unordered_map<int, int> map;
13+
vector<int> arr;
14+
public:
15+
RandomizedSet() {
16+
17+
}
18+
19+
bool insert(int val) {
20+
if (map.find(val) != map.end()) return false;
21+
map[val] = arr.size();
22+
arr.push_back(val);
23+
return true;
24+
}
25+
26+
bool remove(int val) {
27+
if (map.find(val) == map.end()) return false;
28+
int pos = map[val];
29+
map.erase(val);
30+
if (pos == arr.size() - 1) {
31+
arr.erase(arr.end() - 1);
32+
return true;
33+
}
34+
map[arr.back()] = pos;
35+
swap(arr[pos], arr.back());
36+
arr.erase(arr.end() - 1);
37+
return true;
38+
}
39+
40+
int getRandom() {
41+
return arr[rand() % arr.size()];
42+
}
43+
};
44+
45+
/**
46+
* Your RandomizedSet object will be instantiated and called as such:
47+
* RandomizedSet* obj = new RandomizedSet();
48+
* bool param_1 = obj->insert(val);
49+
* bool param_2 = obj->remove(val);
50+
* int param_3 = obj->getRandom();
51+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /