Skip to content

Commit

Permalink
Time: 273 ms (80.64%), Space: 97.1 MB (19.16%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
Dipendra-Raghav committed Nov 29, 2022
1 parent 7ccca36 commit d890858
Showing 1 changed file with 54 additions and 0 deletions.
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();
*/

0 comments on commit d890858

Please sign in to comment.