반응형
https://leetcode.com/problems/insert-delete-getrandom-o1/description
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
insert와 remove는 unordered 자료구조를 이용하여 O(1)에 처리해줍니다.
랜덤한 val을 O(1)에 얻기 위해 insert 시에 vector에도 val을 저장해주고, unordered_map에 각 val의 index도 저장해줍니다.
remove할 때에는, vector에서 삭제된 val에 대한 데이터와 마지막 데이터를 스왑해주고, vector와 unordered_map에서 삭제된 val에 대해 정리해줍니다.
class RandomizedSet {
public:
unordered_map<int, int> s;
vector<int> v;
RandomizedSet() {
}
bool insert(int val) {
auto f = s.find(val);
if(f != s.end()) {
return false;
}
s[val] = v.size();
v.push_back(val);
return true;
}
bool remove(int val) {
auto f = s.find(val);
if(f == s.end()) {
return false;
}
int lastIndex = v.size() - 1;
int lastVal = v.back();
v.pop_back();
int removedIndex = f->second;
v[removedIndex] = lastVal;
s[lastVal] = removedIndex;
s.erase(f);
return true;
}
int getRandom() {
return v[rand() % v.size()];
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 931. Minimum Falling Path Sum (0) | 2024.01.20 |
---|---|
LeetCode 70. Climbing Stairs (0) | 2024.01.18 |
LeetCode 2225. Find Players With Zero or One Losses (0) | 2024.01.15 |
LeetCode 1347. Minimum Number of Steps to Make Two Strings Anagram (0) | 2024.01.13 |
LeetCode 938. Range Sum of BST (0) | 2024.01.08 |