zoukankan      html  css  js  c++  java
  • 最大频率栈 Maximum Frequency Stack

    2018-10-06 22:01:11

    问题描述:

    问题求解:

    为每个频率创建一个栈即可。

    class FreqStack {
        Map<Integer, Integer> map;
        List<Stack<Integer>> stacks;
    
        public FreqStack() {
            map = new HashMap<>();
            stacks = new ArrayList<>();
        }
    
        public void push(int x) {
            int freq = map.getOrDefault(x, 0);
            freq++;
            map.put(x, freq);
            if (freq > stacks.size()) {
                Stack<Integer> stack = new Stack<>();
                stack.push(x);
                stacks.add(stack);
            }
            else {
                Stack<Integer> stack = stacks.get(freq - 1);
                stack.push(x);
            }
        }
    
        public int pop() {
            Stack<Integer> stack = stacks.get(stacks.size() - 1);
            int res = stack.pop();
            if (stack.isEmpty()) stacks.remove(stacks.size() - 1);
            int freq = map.get(res);
            map.put(res, --freq);
            if (freq == 0) map.remove(res);
            return res;
        }
    }
    
    /**
     * Your FreqStack object will be instantiated and called as such:
     * FreqStack obj = new FreqStack();
     * obj.push(x);
     * int param_2 = obj.pop();
     */
    
  • 相关阅读:
    CSUOJ 1554 SG Value
    php面试之四-Linux部分
    php常用算法
    php综合运用技术
    面试基础
    面试题系列1
    面试题系列
    php面试题之五——MySQL数据库(基础部分)
    php面试之数据结构和算法
    asp.net导出Excel类库
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/9748746.html
Copyright © 2011-2022 走看看