forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaximum-frequency-stack.cpp
More file actions
44 lines (37 loc) · 879 Bytes
/
maximum-frequency-stack.cpp
File metadata and controls
44 lines (37 loc) · 879 Bytes
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
// Time: O(1)
// Space: O(n)
class FreqStack {
public:
FreqStack()
: max_freq_(0) {
}
void push(int x) {
++freq_[x];
if (freq_[x] > max_freq_) {
max_freq_ = freq_[x];
}
group_[freq_[x]].emplace_back(x);
}
int pop() {
auto x = group_[max_freq_].back(); group_[max_freq_].pop_back();
if (group_[max_freq_].empty()) {
group_.erase(max_freq_);
--max_freq_;
}
--freq_[x];
if (freq_[x] == 0) {
freq_.erase(x);
}
return x;
}
private:
unordered_map<int, int> freq_;
unordered_map<int, vector<int>> group_;
int max_freq_;
};
/**
* Your FreqStack object will be instantiated and called as such:
* FreqStack obj = new FreqStack();
* obj.push(x);
* int param_2 = obj.pop();
*/