请定义一个队列并实现函数 max_value 获得队列里的最大值,要求函数max_value、push_back 和 pop_front 的时间复杂度都是O(1)。html
若队列为空,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(); */
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(); */