最大频率栈
实现方法
- 为每一个频率维护一个栈(map)
- 为元素维护计数器(map)
- push元素时注意max以及频率栈的更新
- pop元素时注意max、频率栈的删除以及计数器的更新
代码如下
class FreqStack {
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, ArrayDeque<Integer>> freqMap = new HashMap<>();
int max = 0;
public FreqStack() {}
public void push(int val) {
int freq = map.getOrDefault(val, 0) + 1;
max = Math.max(max, freq);
map.put(val, freq);
freqMap.computeIfAbsent(freq, k -> new ArrayDeque<>()).push(val);
}
public int pop() {
ArrayDeque<Integer> stack = freqMap.get(max);
int re = stack.pop();
map.put(re, map.get(re) - 1);
if(stack.isEmpty()) {
freqMap.remove(max--);
}
return re;
}
}转载请注明出处