zoukankan      html  css  js  c++  java
  • 剑指offer59-II-队列的最大值-双向队列Deque

    class MaxQueue {
        Queue<Integer> q1;
        Deque<Integer> q2;
        public MaxQueue() {
            q1=new LinkedList();
            q2=new LinkedList();
        }
        
        public int max_value() {
            if(q2.isEmpty()){
                return -1;
            }
            return q2.peekFirst();
        }
        
        public void push_back(int value) {
            q1.offer(value);
            //只保留对结果有影响的,比如,1,1,1,2,插入value=2,前面1可以从q2去掉,因为要取出1后才取出2,前面1对max没有影响,不会
            //存在取出2之后max是1
            while(!q2.isEmpty()&&q2.peekLast()<value){
                q2.pollLast();
            }
            q2.addLast(value);
        }
        
        public int pop_front() {
            if(q1.isEmpty()){
                return -1;
            }
            int x=q1.poll();
            if(!q2.isEmpty()&&q2.peekFirst()==x){
                q2.pollFirst();
            }
            return x;
        }
    }
    
    /**
     * Your MaxQueue object will be instantiated and called as such:
     * MaxQueue obj = new MaxQueue();
     * int param_1 = obj.max_value();
     * obj.push_back(value);
     * int param_3 = obj.pop_front();
     */
  • 相关阅读:
    归并排序
    堆排序
    数组数据生成器
    冒泡排序
    快速排序
    希尔排序
    排序接口与抽象类(java)
    Pycharm下HTMLTestRunner不生成测试报告
    抓包工具使用记录
    接口学习笔记
  • 原文地址:https://www.cnblogs.com/jieyi/p/14286286.html
Copyright © 2011-2022 走看看