Skip to content

Commit

Permalink
Time: 377 ms (21.25%), Space: 97.3 MB (8.60%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
arpitkekri committed Oct 21, 2021
1 parent 209d1ab commit 644f4f0
Showing 1 changed file with 29 additions and 12 deletions.
41 changes: 29 additions & 12 deletions insert-delete-getrandom-o1/insert-delete-getrandom-o1.cpp
Original file line number Diff line number Diff line change
@@ -1,31 +1,48 @@
class RandomizedSet {
public:
unordered_set<int> s;
map<int, int> mp;
vector<int> arr;
RandomizedSet() {
s.clear();
mp.clear();
arr.clear();
}

bool insert(int val) {
if(s.count(val))
if(mp.count(val))
return false;
s.insert(val);
mp[val] = arr.size();
arr.push_back(val);
return true;
}

bool remove(int val) {
if(s.count(val)) {
s.erase(val);
// bool remove(int val) {
// if(mp.count(val)) {
// int lastElt = arr.back();
// int idx = mp[val];
// arr[idx] = lastElt;
// mp[lastElt] = idx;
// mp.erase(val);
// arr.pop_back();
// return true;
// }
// return false;
// }
bool remove(int val) {
if(mp.count(val)) {
int removeIdx = mp[val];
swap(arr[(int)arr.size()-1], arr[removeIdx]);
mp[arr[removeIdx]] = removeIdx;
mp.erase(val);
arr.pop_back();
return true;
}
return false;
}

int getRandom() {
int n = s.size();
int randNo = rand()%n;
auto itr = s.begin();
advance(itr, randNo);
return *itr;
int n = arr.size();
int randIdx = rand()%n;
return arr[randIdx];
}
};

Expand Down

0 comments on commit 644f4f0

Please sign in to comment.