added randomizedset

This commit is contained in:
wt committed 2026-04-08 17:55:26 +07:00
1 parent ea3d15f694
commit 1bb417d151
8 files changed
+100 -1

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
#include <cassert>
#include <iostream>
#include "randomizedset.hpp"
int main() {
RandomizedSet *randomizedSet = new RandomizedSet();
bool res = randomizedSet->insert(1);
std::cout << res << std::endl;
assert(res == true);
res = randomizedSet->remove(2);
std::cout << res << std::endl;
assert(res == false);
res = randomizedSet->insert(2);
std::cout << res << std::endl;
assert(res == true);
int ires = randomizedSet->getRandom();
std::cout << ires << std::endl; // Функция getRandom() должна возвращать
// случайным образом либо 1, либо 2.
res = randomizedSet->remove(1);
std::cout << res << std::endl;
assert(res == true);
res = randomizedSet->insert(2);
std::cout << res << std::endl;
assert(res == false);
ires = randomizedSet->getRandom();
std::cout << ires << std::endl;
assert(ires == 2);
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
#include <cstdlib>
#include <ctime>
#include <unordered_map>
#include <vector>
class RandomizedSet {
public:
RandomizedSet() {
srand(time(nullptr));
}
bool insert(int val) {
if (map.find(val) != map.end()) return false;
map[val] = list.size();
list.push_back(val);
return true;
}
bool remove(int val) {
auto it = map.find(val);
if (it == map.end()) return false;
int idx = it->second;
int lastVal = list.back();
list[idx] = lastVal;
map[lastVal] = idx;
list.pop_back();
map.erase(it);
return true;
}
int getRandom() {
return list[rand() % list.size()];
}
private:
std::vector<int> list;
std::unordered_map<int, int> map;
};