add: 220316-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-16 15:31:40 +08:00
parent 8b0a1dcc49
commit d6f6ffecff
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 82 additions and 1 deletions

81
cpp/2203/220316-CN.cpp Normal file
View File

@ -0,0 +1,81 @@
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
class AllOne {
private:
int n = 0;
std::unordered_map<int, std::string> id2Str;
std::unordered_map<std::string, int> str2Id;
std::map<int, std::unordered_set<int>> val2Id;
std::unordered_map<int, int> id2Val;
public:
AllOne() = default;
void inc(const std::string& key) {
if (str2Id.count(key)) {
int idx = str2Id[key];
int& val = id2Val[idx];
if (val2Id[val].size() == 1) {
val2Id.erase(val);
} else {
val2Id[val].erase(idx);
}
val2Id[++val].insert(idx);
} else {
int x = str2Id[key] = ++n;
id2Str[x] = key;
id2Val[x] = 1;
val2Id[1].insert(x);
}
}
void dec(const std::string& key) {
int idx = str2Id[key];
int& val = id2Val[idx];
if (val == 1) {
id2Str.erase(idx);
if (val2Id[1].size() == 1)
val2Id.erase(1);
else
val2Id[1].erase(idx);
str2Id.erase(key);
id2Val.erase(idx);
} else {
if (val2Id[val].size() == 1) {
val2Id.erase(val);
} else {
val2Id[val].erase(idx);
}
val2Id[--val].insert(idx);
}
}
std::string getMaxKey() {
return str2Id.empty() ? "" : id2Str[*(val2Id.rbegin()->second.begin())];
}
std::string getMinKey() {
return str2Id.empty() ? "" : id2Str[*(val2Id.begin()->second.begin())];
}
};
int main() {
AllOne test;
test.inc("hello");
test.inc("hello");
std::cout << test.getMaxKey() << std::endl;
std::cout << test.getMinKey() << std::endl;
test.inc("123");
std::cout << test.getMaxKey() << std::endl;
std::cout << test.getMinKey() << std::endl;
test.dec("hello");
std::cout << test.getMaxKey() << std::endl;
std::cout << test.getMinKey() << std::endl;
test.dec("hello");
std::cout << test.getMaxKey() << std::endl;
std::cout << test.getMinKey() << std::endl;
}

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220316.cpp) ADD_EXECUTABLE(2203 220316-CN.cpp)