leetcode 895. Maximum Frequency Stack(最大频率栈)

2022/3/19 23:58:33

本文主要是介绍leetcode 895. Maximum Frequency Stack(最大频率栈),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.

Implement the FreqStack class:

FreqStack() constructs an empty frequency stack.
void push(int val) pushes an integer val onto the top of the stack.
int pop() removes and returns the most frequent element in the stack.
If there is a tie for the most frequent element, the element closest to the stack’s top is removed and returned.

Example 1:

Input
[“FreqStack”, “push”, “push”, “push”, “push”, “push”, “push”, “pop”, “pop”, “pop”, “pop”]
[[], [5], [7], [5], [7], [4], [5], [], [], [], []]
Output
[null, null, null, null, null, null, null, 5, 7, 5, 4]

Explanation
FreqStack freqStack = new FreqStack();
freqStack.push(5); // The stack is [5]
freqStack.push(7); // The stack is [5,7]
freqStack.push(5); // The stack is [5,7,5]
freqStack.push(7); // The stack is [5,7,5,7]
freqStack.push(4); // The stack is [5,7,5,7,4]
freqStack.push(5); // The stack is [5,7,5,7,4,5]
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].
freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].
freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].

写一个返回最大频率元素的stack。

思路:
既然是stack就要满足后进先出,还要记录频率。

那么需要一个变量maxFreq记录最大频率,
一个HashMap记录每个数字对应的出现频率。
当pop时,需要知道maxFreq对应的有哪些元素,及元素的push的先后顺序。
所以还需要一个HashMap用来保存每个出现频率对应的有哪些元素,这些元素要按push的顺序保存。

push时,首先要给对应数字的频率+1;该频率对应的list中加入push的数字。
然后更新maxFreq。
(注意:比如5出现了3次,那么map中(频率,数字list)对中要保存(1, [5]), (2, [5]), (3, [5]))

pop时,因为知道maxFreq,所以直接从HashMap中找到对应的数字list,
list中的数字是按push的顺序保存的,所以直接返回最后一个数字,并删除它;该数字对应的频率也要-1。
当list为空时,说明该maxFreq对应的已经没有数字了,maxFreq要-1。

class FreqStack {
    HashMap<Integer, List<Integer>> map = new HashMap<>();
    HashMap<Integer, Integer> freq = new HashMap<>();
    int maxFreq = 0;
    int fq = 0;
    
    public FreqStack() {
        
    }
    
    public void push(int val) {
        freq.put(val, freq.getOrDefault(val, 0) + 1);
        fq = freq.get(val);
        
        maxFreq = Math.max(maxFreq, fq);
        if(!map.containsKey(fq)) {
            map.put(fq, new ArrayList<Integer>());
        }
        map.get(fq).add(val);
    }
    
    public int pop() {
        int len = map.get(maxFreq).size();
        int element = map.get(maxFreq).remove(len - 1);
        freq.put(element, freq.get(element) - 1);
        if(len == 1) {
            maxFreq --;
        }
        return element;
    }
}


这篇关于leetcode 895. Maximum Frequency Stack(最大频率栈)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程