1. 题目
2. 题解
- 维持两个Map + 一个变量记录当前最大频率
- 一个Map存储:当前元素——元素频率
- 一个Map存储:频率——频率对应元素(用栈存储)
class FreqStack {
Map<Integer, Integer> freq;
Map<Integer, Deque<Integer>> group;
int maxfreq;
public FreqStack() {
freq = new HashMap();
group = new HashMap();
maxfreq = 0;
}
public void push(int x) {
int f = freq.getOrDefault(x, 0) + 1;
freq.put(x, f);
if(f > maxfreq)
maxfreq = f;
group.computeIfAbsent(f, k -> new LinkedList()).push(x);
}
public int pop() {
int x = group.get(maxfreq).pop();
freq.put(x, freq.get(x) - 1);
if(group.get(maxfreq).size() == 0)
maxfreq--;
return x;
}
}
|