From 58d9ac315d1563bae77e5bcfb9f9e615f7590514 Mon Sep 17 00:00:00 2001 From: eat-swap Date: Fri, 15 Apr 2022 23:14:40 +0800 Subject: [PATCH] add: 220413-CN [cpp] --- cpp/2204/220413-CN.cpp | 62 +++++++++++++++++++++++++++++++++++++++-- cpp/2204/CMakeLists.txt | 2 +- 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/cpp/2204/220413-CN.cpp b/cpp/2204/220413-CN.cpp index 6202926..51c7b74 100644 --- a/cpp/2204/220413-CN.cpp +++ b/cpp/2204/220413-CN.cpp @@ -1,2 +1,60 @@ -#include -#include \ No newline at end of file +#include +#include +#include + +/** + * 380. Insert Delete GetRandom O(1) + * Implement the RandomizedSet class: + * RandomizedSet() Initializes the RandomizedSet object. + * bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. + * bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. + * int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. + * You must implement the functions of the class such that each function works in average O(1) time complexity. + */ + +class RandomizedSet { + // m[number] -> idx + std::unordered_map m; + + // v[idx] -> number + std::vector v; +public: + RandomizedSet() { + std::srand(std::time(nullptr)); + } + + bool insert(int val) { + if (m.count(val)) + return false; + m[val] = v.size(); + v.push_back(val); + return true; + } + + bool remove(int val) { + if (!m.count(val)) + return false; + v[m[val]] = v.back(); + m[v.back()] = m[val]; + v.pop_back(); + m.erase(val); + return true; + } + + int getRandom() const { + return v[std::rand() % v.size()]; + } +}; + +int main() { + auto s = new RandomizedSet; + + s->insert(0); + s->insert(1); + s->remove(0); + s->insert(2); + s->remove(1); + int x = s->getRandom(); + + return 0; +} diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index 222e83c..b3f2d3c 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220415-CN.cpp) +ADD_EXECUTABLE(2204 220413-CN.cpp)