add data-structure of number container and priority manager
change example 3479
This commit is contained in:
35
data-structure/number-containers.cpp
Normal file
35
data-structure/number-containers.cpp
Normal 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();
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user