Skip to content

Commit

Permalink
feat(C++): Add 2349
Browse files Browse the repository at this point in the history
  • Loading branch information
euchangxian committed Oct 22, 2024
1 parent 2a3b60f commit 77375fd
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
58 changes: 58 additions & 0 deletions C++/2349-DesignANumberContainerSystem/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#include <cstddef>
#include <set>
#include <unordered_map>

using namespace std;
/**
* Seems to be a many-to-one relationship between Buckets/Containers and
* Numbers.
* Each Container can store only one Number, but each Number may be stored in
* multiple Containers.
*
* 1 <= index, number <= 10^9. => 4MB of integers possible => unordered_map
* should be used instead of an array.
*
* Naively, seems like two unordered_map is sufficient.
* One for bucket -> number
* The other for number -> {bucket1, ...}
*
* For the number -> buckets, use an ordered Set.
*/
class NumberContainers {
private:
std::unordered_map<int, int> containers;
std::unordered_map<int, std::set<int>> numbers;

public:
NumberContainers() {}

void change(int index, int number) {
auto iter = containers.find(index);
if (iter != containers.end()) {
int original = iter->second;
numbers[original].erase(index);

if (numbers[original].empty()) {
numbers.erase(original);
}
}
containers[index] = number;
numbers[number].insert(index);
}

int find(int number) {
auto iter = numbers.find(number);
if (iter == numbers.end()) {
return -1;
}

return *(iter->second).begin();
}
};

/**
* Your NumberContainers object will be instantiated and called as such:
* NumberContainers* obj = new NumberContainers();
* obj->change(index,number);
* int param_2 = obj->find(number);
*/
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ Now solving in C++. Like it.
| 2331 | EvaluateBooleanBinaryTree | [![Rust](assets/rust.svg)](Rust/2331-EvaluateBooleanBinaryTree/Solution.rs) [![C++](assets/c++.svg)](C++/2331-EvaluateBooleanBinaryTree/Solution.cpp) |
| 2334 | SubarrayWithElementsGreaterThanVaryingThreshold | [![C++](assets/c++.svg)](C++/2334-SubarrayWithElementsGreaterThanVaryingThreshold/Solution.cpp) |
| 2336 | SmallestNumberInInfiniteSet | [![C++](assets/c++.svg)](C++/2336-SmallestNumberInInfiniteSet/Solution.cpp) |
| 2349 | DesignANumberContainerSystem | [![C++](assets/c++.svg)](C++/2349-DesignANumberContainerSystem/Solution.cpp) |
| 2373 | LargestLocalValuesInAMatrix | [![Rust](assets/rust.svg)](Rust/2373-LargestLocalValuesInAMatrix/Solution.rs) |
| 2392 | BuildAMatrixWithConditions | [![C++](assets/c++.svg)](C++/2392-BuildAMatrixWithConditions/Solution.cpp) |
| 2393 | CountStrictlyIncreasingSubarrays | [![C++](assets/c++.svg)](C++/2393-CountStrictlyIncreasingSubarrays/Solution.cpp) |
Expand Down

0 comments on commit 77375fd

Please sign in to comment.