-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 273 ms (80.64%), Space: 97.1 MB (19.16%) - LeetHub
- Loading branch information
1 parent
7ccca36
commit d890858
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
54 changes: 54 additions & 0 deletions
54
0380-insert-delete-getrandom-o1/0380-insert-delete-getrandom-o1.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
class RandomizedSet { | ||
public: | ||
vector<int> vec; | ||
unordered_map<int,int> mp; | ||
RandomizedSet() { | ||
|
||
} | ||
|
||
bool insert(int val) { | ||
if(mp.find(val)!=mp.end()) | ||
{ | ||
return false; | ||
} | ||
vec.push_back(val); | ||
mp[val]=vec.size()-1; | ||
return true; | ||
|
||
} | ||
|
||
bool remove(int val) { | ||
if(mp.find(val)!=mp.end()) | ||
{ | ||
int ind=mp[val]; | ||
int last=vec.back(); | ||
vec.back()=val; | ||
vec[ind]=last; | ||
mp[last]=ind; | ||
vec.pop_back(); | ||
mp.erase(val); | ||
return true; | ||
|
||
|
||
} | ||
return false; | ||
|
||
|
||
|
||
} | ||
|
||
int getRandom() { | ||
int n=vec.size(); | ||
int num=rand()%n; | ||
return vec[num]; | ||
|
||
} | ||
}; | ||
|
||
/** | ||
* Your RandomizedSet object will be instantiated and called as such: | ||
* RandomizedSet* obj = new RandomizedSet(); | ||
* bool param_1 = obj->insert(val); | ||
* bool param_2 = obj->remove(val); | ||
* int param_3 = obj->getRandom(); | ||
*/ |