請定義一個隊列並實現函數 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(); */