-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily104.cpp
More file actions
83 lines (64 loc) · 2 KB
/
Copy pathdaily104.cpp
File metadata and controls
83 lines (64 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Solution 1 - unfinished
class AllOne {
public:
AllOne() {
}
void inc(string key) {
}
void dec(string key) {
}
string getMaxKey() {
}
string getMinKey() {
}
};
/**
* Your AllOne object will be instantiated and called as such:
* AllOne* obj = new AllOne();
* obj->inc(key);
* obj->dec(key);
* string param_3 = obj->getMaxKey();
* string param_4 = obj->getMinKey();
*/
// Solution 2
class AllOne {
public:
unordered_map<string,int> count; // Stores the count of each key
set<pair<int,string>> se; // Sorted set to keep counts and keys
AllOne() {
count.clear(); // Initialize the count map
}
// Increment the count of the key
void inc(string key) {
int n = count[key]; // Get current count
count[key]++; // Increment the count
se.erase({n, key}); // Remove the old pair from set
se.insert({n+1, key}); // Insert the new pair with updated count
}
// Decrement the count of the key
void dec(string key) {
int n = count[key]; // Get current count
count[key]--; // Decrement the count
se.erase({n, key}); // Remove the old pair from set
if (count[key] > 0) se.insert({n-1, key}); // If count > 0, insert updated pair
else count.erase(key); // If count reaches 0, remove the key from map
}
// Get the key with the maximum count
string getMaxKey() {
if (!se.empty()) return se.rbegin()->second; // Last element gives the maximum
return "";
}
// Get the key with the minimum count
string getMinKey() {
if (!se.empty()) return se.begin()->second; // First element gives the minimum
return "";
}
};
/**
* Your AllOne object will be instantiated and called as such:
* AllOne* obj = new AllOne();
* obj->inc(key);
* obj->dec(key);
* string param_3 = obj->getMaxKey();
* string param_4 = obj->getMinKey();
*/