add data-structure of number container and priority manager

change example 3479
This commit is contained in:
2025-09-18 19:31:20 +08:00
parent 80b6e4fcaf
commit 57dd0e9440
3 changed files with 89 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
#include <unordered_map>
#include <queue>
#include <vector>
/*
The number container system can do the following:
1. insert or replace a number at the given index
2. return the smallest index for the given number in the system
*/
class NumberContainers {
private:
std::unordered_map<int, int> nums;
std::unordered_map<int, std::priority_queue<int, std::vector<int>, std::greater<int>>> heap;
public:
NumberContainers() = default;
void change(int index, int number) {
nums[index] = number;
heap[number].push(index);
}
int find(int number) {
while (!heap[number].empty() && nums[heap[number].top()] != number) {
heap[number].pop();
}
if (heap[number].empty()) {
return -1;
}
return heap[number].top();
}
};