-
Notifications
You must be signed in to change notification settings - Fork 14
/
FreqStack.java
41 lines (31 loc) · 917 Bytes
/
FreqStack.java
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
package leetcode.hashmap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FreqStack {
HashMap<Integer, Integer> numFreq;
HashMap<Integer, List<Integer>> freqNum;
int maxFreq;
public FreqStack() {
numFreq = new HashMap<>();
freqNum = new HashMap<>();
maxFreq = 0;
}
public void push(int val) {
int freq = numFreq.getOrDefault(val, 0) + 1;
numFreq.put(val, freq);
maxFreq = Math.max(maxFreq, freq);
List<Integer> list = freqNum.getOrDefault(freq, new ArrayList<>());
list.add(val);
freqNum.put(freq, list);
}
public int pop() {
List<Integer> list = freqNum.get(maxFreq);
Integer res = list.remove(list.size() - 1);
numFreq.put(res, maxFreq - 1);
if (list.size() == 0) {
maxFreq--;
}
return res;
}
}