Skip to content

Commit

Permalink
이슈 #449에서 솔루션 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
actions-user committed Dec 26, 2024
1 parent 704c052 commit 0840283
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions LeetCode/Insert_Delete_GetRandom_O1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
class RandomizedSet {
public:
RandomizedSet() {}

bool insert(int val) {
if (valToIndex.find(val) != valToIndex.end()) {
return false;
}

values.push_back(val);
valToIndex[val] = values.size() - 1;

return true;
}

bool remove(int val) {
if (valToIndex.find(val) == valToIndex.end()) {
return false;
}

int lastElement = values.back();
int indexToRemove = valToIndex[val];

values[indexToRemove] = lastElement;
valToIndex[lastElement] = indexToRemove;

values.pop_back();
valToIndex.erase(val);

return true;
}

int getRandom() {
int randomindex = rand() % values.size();
return values[randomindex];
}

private:
unordered_map<int, int> valToIndex;
vector<int> values;
};

/**
* 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 0840283

Please sign in to comment.