-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxFreqStack.java
More file actions
42 lines (30 loc) · 827 Bytes
/
MaxFreqStack.java
File metadata and controls
42 lines (30 loc) · 827 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
class FreqStack {
HashMap<Integer, Integer> freq;
HashMap<Integer, Stack<Integer>> group;
int maxFreq;
public FreqStack() {
freq = new HashMap<>();
group = new HashMap<>();
maxFreq = 0;
}
public void push(int val) {
int f = freq.getOrDefault(val, 0) + 1;
freq.put(val, f);
maxFreq = Math.max(maxFreq, f);
group.computeIfAbsent(f, z -> new Stack<>()).push(val);
}
public int pop() {
int val = group.get(maxFreq).pop();
freq.put(val, freq.get(val) - 1);
if(group.get(maxFreq).isEmpty()){
maxFreq--;
}
return val;
}
}
/**
* Your FreqStack object will be instantiated and called as such:
* FreqStack obj = new FreqStack();
* obj.push(val);
* int param_2 = obj.pop();
*/