面试题59

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的时间复杂度都是O(1)。

若队列为空,pop_front 和 max_value 需要返回 -1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题可以和之前的那个单调栈放在一起看单调栈
1. 使用大顶堆来实现,传入comparator比较器。比较简单无脑。

class MaxQueue {
    private LinkedList<Integer> list;
    private PriorityQueue<Integer> max; 
    private Comparator<Integer> cam=new Comparator<>(){
            public int compare(Integer o1,Integer o2)
            {
                return o2-o1;
            }
       };
    public MaxQueue() {
       list=new LinkedList<>();
       max=new PriorityQueue<>(cam);
    }
    
    public int max_value() {
        return max.isEmpty()?-1:max.peek();
    }
    
    public void push_back(int value) {
        list.addLast(value);
        max.add(value);
    }
    
    public int pop_front() {
        if(list.isEmpty())
            return -1;
       int front=list.getFirst();
       if(!max.isEmpty())
            max.remove(front);
        return list.remove();
    }
}

/**
 * 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();
 */
  1. 使用两个队列来实现,原理是入队时一个正常出入队,一个是max队,存放最大值信息,这里的关键是对于入队而言,如果入队的这个值要比队列最后一个值要小,那么可以直接入队,不然大的话,就要删去前面比它小的值,容易理解为对于list而言这个位置比之前的几个位置的最大值大的话,那么他就是最大值了,所以max队列的结构是降序排列的,如果出现一个最大的要加入,那么之前所有元素都要去除,如果不是最大,那么也要去除在他之前比他大的元素,知道遇到一个比他要小的。
class MaxQueue {
    private LinkedList<Integer> list;
    private LinkedList<Integer> max;
   
    public MaxQueue() {
       list=new LinkedList<>();
       max=new LinkedList<>();
    }
    
    public int max_value() {
      if(max.isEmpty())
        return -1;
      return max.peek();
    }
    
    public void push_back(int value) {
      list.add(value);
      
      while(!max.isEmpty()&&max.getLast()<value)
          max.pollLast();
      max.add(value);
    }
    
    public int pop_front() {
        if(list.isEmpty())
            return -1;
        int front =list.pollFirst();
        if(front==max.peek())
            max.remove();
        return front;
    }
}

/**
 * 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();
 */
原文地址:https://www.cnblogs.com/cold-windy/p/12437081.html