|
| 1 | +## 716. Max Stack |
| 2 | + |
| 3 | +### Question |
| 4 | +Design a max stack that supports push, pop, top, peekMax and popMax. |
| 5 | + |
| 6 | +push(x) -- Push element x onto stack. |
| 7 | +pop() -- Remove the element on top of the stack and return it. |
| 8 | +top() -- Get the element on the top. |
| 9 | +peekMax() -- Retrieve the maximum element in the stack. |
| 10 | +popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one. |
| 11 | + |
| 12 | +``` |
| 13 | +Example 1: |
| 14 | +MaxStack stack = new MaxStack(); |
| 15 | +stack.push(5); |
| 16 | +stack.push(1); |
| 17 | +stack.push(5); |
| 18 | +stack.top(); -> 5 |
| 19 | +stack.popMax(); -> 5 |
| 20 | +stack.top(); -> 1 |
| 21 | +stack.peekMax(); -> 5 |
| 22 | +stack.pop(); -> 1 |
| 23 | +stack.top(); -> 5 |
| 24 | +``` |
| 25 | + |
| 26 | +Note: |
| 27 | +1. -1e7 <= x <= 1e7 |
| 28 | +2. Number of operations won't exceed 10000. |
| 29 | +3. The last four operations won't be called when stack is empty. |
| 30 | + |
| 31 | +### Solutions |
| 32 | +* Method 1: LinkedList + PriorityQueue |
| 33 | + ```Java |
| 34 | + class MaxStack { |
| 35 | + private PriorityQueue<Integer> pq; |
| 36 | + private LinkedList<Integer> values; |
| 37 | + /** initialize your data structure here. */ |
| 38 | + public MaxStack() { |
| 39 | + this.pq = new PriorityQueue<>(new Comparator<Integer>(){ |
| 40 | + @Override |
| 41 | + public int compare(Integer a, Integer b){ |
| 42 | + return b - a; |
| 43 | + } |
| 44 | + }); |
| 45 | + this.values = new LinkedList<>(); |
| 46 | + } |
| 47 | + |
| 48 | + public void push(int x) { |
| 49 | + this.values.addFirst(x); |
| 50 | + this.pq.offer(x); |
| 51 | + } |
| 52 | + |
| 53 | + public int pop() { |
| 54 | + Integer first = this.values.pollFirst(); |
| 55 | + pq.remove(first); |
| 56 | + return first; |
| 57 | + } |
| 58 | + |
| 59 | + public int top() { |
| 60 | + return this.values.get(0); |
| 61 | + } |
| 62 | + |
| 63 | + public int peekMax() { |
| 64 | + return this.pq.peek(); |
| 65 | + } |
| 66 | + |
| 67 | + public int popMax() { |
| 68 | + Integer max = pq.poll(); |
| 69 | + this.values.remove(max); |
| 70 | + return max; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Your MaxStack object will be instantiated and called as such: |
| 76 | + * MaxStack obj = new MaxStack(); |
| 77 | + * obj.push(x); |
| 78 | + * int param_2 = obj.pop(); |
| 79 | + * int param_3 = obj.top(); |
| 80 | + * int param_4 = obj.peekMax(); |
| 81 | + * int param_5 = obj.popMax(); |
| 82 | + */ |
| 83 | + ``` |
0 commit comments