最大频率栈

实现方法

代码如下

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;
    }
}
转载请注明出处